【发布时间】:2021-03-23 20:21:14
【问题描述】:
这是我正在做的工作版本。
#include <memory>
using namespace std;
struct thing {
int blah;
};
struct parentObj {
parentObj(thing & incomingThing) : isThisOK(incomingThing) {};
thing & isThisOK;
};
int main()
{
shared_ptr<thing> thingInstance = make_shared<thing>();
shared_ptr<parentObj> theObj = make_shared<parentObj>(*thingInstance);
}
我喜欢将共享指针分配给它的类型的引用。 (ctrl+f isThisOK)
这里有意想不到的后果吗?我应该使用弱指针吗?
【问题讨论】:
-
这就像保存对任何其他对象的引用一样好。这意味着,编译器不会为您捕获对象生命周期错误,这个负担就在您的肩上。
-
它可以编译,但我不确定这是
shared_ptr的最佳用途。parentObj对thing&的引用不允许它知道何时访问它是有效的。您可能根本不使用shared_ptr。 -
一个大问题是,一旦
theObj的引用为零,它就会破坏其底层对象,thingInstance即使不再存在,它仍将指向它。 -
@sanitizedUser 错误,默认销毁不销毁引用数据成员。
-
这段代码没问题,但我想你的实际代码更复杂——你必须保证一旦thingInstance被销毁,那么Obj就不会使用它的引用(否则你会得到UB)。您可以将 std::weak_ptr 传递给 parentObj 以防止 UB
标签: c++ shared-ptr smart-pointers