[英]Temporary boost::shared_ptr when passing to constructor of superclass
[英]Passing shared_ptr of this in constructor
我有如下代碼
class Task;
class Attribute
{
public:
Attribute(Task* task, std::string name);
std::shared_ptr<Task> task_;
std::string name_;
};
class Task : std::enable_shared_from_this<Task>
{
public:
std::shared_ptr<Task> getSharedPtr()
{
return this->shared_from_this();
}
Attribute att1_ = {this, "attribute1"};
Attribute att2_ = {this, "attribute2"};
};
Attribute::Attribute(Task* task, std::string name)
: name_(name)
{
task_ = task->getSharedPtr();
}
當我運行它時,我得到一個
$ terminate called after throwing an instance of 'std::bad_weak_ptr'
從這個問題我得到我不能調用shared_from_this()
直到對象被完全構造。 我想這意味着我無法在構造函數中創建Attribute
類型的對象,但是我應該在構造函數結束后實例化它們。
您是否知道這是克服此問題的一種方法,因為對於我而言,必須實例化不在構造函數中的Attribute對象真的很煩人。
我想你跌倒的這個規則的犯規,按照這個 :
請注意,在對對象t調用shared_from_this之前,必須有一個擁有t的std :: shared_ptr。
您似乎想重新考慮Task
與Attribute
之間的所有權關系,這很奇怪(如果Task
擁有其Attributes
,為什么他們需要對他們的Task
shared_ptr
?)。
由於Task
擁有 Attribute
,因此Attribute
無需與Task
共享所有權-他們不必擔心將Task
淘汰。 您可以只使用原始指針:
class Attribute
{
public:
Attribute(Task* task, std::string name);
Task* task_;
std::string name_;
};
或者,如果您想更明確地表達語義,請使用observer_ptr<Task>
。
請注意,您必須具有用於Task
的復制/移動構造函數/賦值運算符,才能正確地重新分配屬性以指向新Task
而不是舊Task
。
當我在std :: enable_shared_from_this前面忘記“ public”時,遇到了同樣的錯誤(在Mac上)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.