我发现这个方法运作良好,但不知道这个方法是否安全,因为我不知道为什么会这样:
struct X{
static X& make(){
return *std::make_shared<X>();
}
...
}
int main(){
const auto& a = X::make();
a.function();
...
// seems like the instance holds and nothing broken
}
Run Code Online (Sandbox Code Playgroud)
以我的理解,从中返回的对已取消引用的对象的引用shared_ptr operator*不应影响如何shared_ptr管理实例的引用计数:因此,内部创建的实例make()应在make()完成后销毁。但是这种代码模式已经运行了很多次,我不明白为什么。因此,我不确定我们是否真的可以通过这种方式做到这一点……感谢任何评论!