我什至不确定我是否完全理解你的问题,但让我试一试:你能用std::weak_ptr
吗?
考虑以下(人为的)示例:
#include<memory>
#include<iostream>
class Renderer {
public:
Renderer()
: m_calls(0) { }
void render() {
m_calls++;
std::cout<<"Issued render call #"<<m_calls<<std::endl;
}
void reset() {
std::cout<<"Reset called"<<std::endl;
m_calls = 0;
}
private:
size_t m_calls;
};
class Context {
public:
Context(std::shared_ptr<Renderer> prenderer)
: m_prenderer(prenderer) {
}
void build_cache() {
if(auto renderer = m_prenderer.lock()) {
renderer->render();
} else {
std::cout<<"Handle the case when I don't have a renderer to work with"<<std::endl;
}
}
private:
std::weak_ptr<Renderer> m_prenderer;
};
int main() {
auto renderer = std::make_shared<Renderer>();
Context ctx(renderer);
ctx.build_cache();
ctx.build_cache();
std::cout<<"Here I reset the renderer"<<std::endl;
renderer->reset();
ctx.build_cache();
}
编译为:g++ example.cpp -std=c++11
(gcc 4.7.2)。输出:
Issued render call #1
Issued render call #2
Here I reset the renderer
Reset called
Issued render call #1
的目的std::weak_ptr
是共享指针而不共享所有权。因此,您可以重置或完全重新创建您Renderer
的Context
. 此外,对空指针的取消引用具有明确定义的行为。