Cur*_*ous 1 c++ smart-pointers c++11
这里的类似问题似乎都使用了boost,我没有使用它.
我想要做的是通过以下方式证明:
在"所有者"中:
std::shared_ptr<State> m_state;
m_state = make_shared<State>(param);
m_state = m_state->SomeVirtualFunction(); // The original m_state object gets destroyed
Run Code Online (Sandbox Code Playgroud)
在"拥有":
std::shared_ptr<State> State::SomeVirtualFunction() {
return std:shared_ptr<State>(this);
}
Run Code Online (Sandbox Code Playgroud)
在MSVS 2012中的Visual C++中,拥有的对象被破坏.我该如何保持活力?
你需要继承std::enable_shared_from_this; 看看`enable_shared_from_this`的用处是什么?. std::enable_shared_from_this为您的类型配备shared_from_this您调用的成员函数,而不是std::shared_ptr<State>(this):
std::shared_ptr<State> State::SomeVirtualFunction() {
return shared_from_this();
}
Run Code Online (Sandbox Code Playgroud)
此前C++ 11(或升压,这是在C++ 11获得enable_shared_from_this来自),并假设你有一个shared_ptr不提供实现enable_shared_from_this,您可以通过给手工做State一个weak_ptr本身,它可以转换成shared_ptr什么时候需要:
class State {
...
std::weak_ptr<State> weak_self;
};
m_state = make_shared<State>(param);
m_state->weak_self = m_state;
std::shared_ptr<State> State::SomeVirtualFunction() {
return weak_self.lock()
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2180 次 |
| 最近记录: |