【问题标题】:C++11 Passing 'this' as paramenter for std::make_sharedC++11 将“this”作为参数传递给 std::make_shared
【发布时间】:2012-05-10 12:40:29
【问题描述】:

我正在尝试使用 std::make_shared 将“this”传递给构造函数

例子:

// headers
class A 
{
public:
   std::shared_ptr<B> createB();
}


class B 
{
private:
   std::shared_ptr<A> a;

public:
   B(std::shared_ptr<A>);
}


// source
std::shared_ptr<B> A::createB()
{
   auto b = std::make_shared<B>(this); // Compiler error (VS11 Beta)
   auto b = std::make_shared<B>(std::shared_ptr<A>(this)); // No compiler error, but doenst work
   return b;
}

但是这不能正常工作,有什么建议我可以正确地将它作为参数传递吗?

【问题讨论】:

  • “不能正常工作” - 为什么不呢?发生什么了?为什么这么糟糕?请用非概括性描述问题,以便未来的读者可以通过搜索词找到它们。

标签: c++ constructor c++11 this make-shared


【解决方案1】:

我想你可能想要的是shared_from_this

// headers
class A : std::enable_shared_from_this< A >
{
public:
   std::shared_ptr<B> createB();
}


class B 
{
private:
   std::shared_ptr<A> a;

public:
   B(std::shared_ptr<A>);
}


// source
std::shared_ptr<B> A::createB()
{
   return std::make_shared<B>( shared_from_this() );
}

更新以包含comments from David Rodriguez

请注意,shared_from_this() 不应该在尚未由shared_ptr 管理的对象上调用。这是有效的:

shared_ptr<A> a( new A );
a->createB();

虽然以下会导致未定义的行为(尝试在 a 上调用 delete):

A a;
a.createB();

【讨论】:

  • 重要的是要注意shared_from_this() 要求当前对象已经在shared_ptr 中管理。 IE。 int main() { A a; a.createB(); } 是未定义的行为,而 int main() { shared_ptr&lt;A&gt; a( new A ); a-&gt;createB(); } 是正确的。
  • @DavidRodríguez-dribeas 绝对。我已经相应地更新了答案。谢谢。
猜你喜欢
  • 2014-01-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-03-31
  • 1970-01-01
  • 1970-01-01
  • 2016-03-13
相关资源
最近更新 更多