是否可以使用对shared_ptr拥有的对象的引用
Is it OK to use reference to the object owned by a shared_ptr?
我发现这运行良好,但不知道这是否安全,因为我不明白它为什么有效:
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
}
在我的理解中,从shared_ptr
operator*
中返回对 derefed 对象的引用不应影响shared_ptr
管理实例引用计数的方式:因此make()
中创建的实例应在make()
完成后销毁。但是这种代码模式已经运行了很多次,我不明白为什么。所以我不确定我们是否真的能以这种方式做到这一点......感谢任何评论!
不,从 make_shared
返回的共享指针在返回后会立即被销毁,因此通过取消引用它获得的引用将悬而未决。它可能看起来有效,但它实际上只是未定义的行为,并且如注释中所述,未定义是未定义的。
相关文章:
- 是否可以获取成员函数模板参数的拥有对象?
- 拥有或在对象之间共享资源
- googlemock-如何模拟被测试类所拥有的对象
- C++ shared_ptr调用拥有对象的解构函数
- 在另一个 QThread 上运行成员方法时,无法将事件发送到其他线程拥有的对象
- 使用 lambda/std::function 删除拥有该函数的对象
- QT:QT无法将事件发送到另一个线程拥有的对象 - 原因
- 当 std::unique_ptr 在手动删除其拥有的对象后超出范围时,它如何工作?
- 谁拥有QQMlinCubator返回的对象
- 带有 std::map 的 c++ 结构是拥有动态数据对象的好设计吗?
- 是否可以使用对shared_ptr拥有的对象的引用
- 将原始指针向量清除给由独特指针拥有的对象
- 如何将 QEvent 传递给接收者拥有的对象?
- 如何正确地使一个对象拥有另一个多态对象
- C++拥有持久对象的最佳方式
- 将类的实例传递给另一个构造函数,该构造函数将其对象添加到所传递实例所拥有的列表中
- C++正在更改子类中拥有的对象类型
- 如何将此的shared_ptr返回给拥有它的对象
- 类同时拥有和共享对象
- 如何根据模板类型拥有对象向量