C ++ 11将“ this”作为std :: make_shared的参数传递 [英] C++11 Passing 'this' as paramenter for std::make_shared

查看:583
本文介绍了C ++ 11将“ this”作为std :: make_shared的参数传递的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用std :: make_shared

I'm trying to pass 'this' to the constructor using std::make_shared

示例:

// 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;
}

但是,这不能正常工作,我建议如何正确通过

However this does not work properly, any suggestions how I can properly pass this as an argument?

推荐答案

我认为您可能想要的是 shared_from_this

I think what you probably want here is 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() );
}






更新为包含 David Rodriguez的评论

请注意, shared_from_this()不应从不调用尚未由<$管理的对象c $ c> shared_ptr 。这是有效的:

Note that shared_from_this() should never be called on an object that isn't already managed by a shared_ptr. This is valid:

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

尽管以下情况导致不确定的行为(试图调用 delete a 上的c $ c>):

While the following leads to undefined behaviour (attempting to call delete on a):

A a;
a.createB();

这篇关于C ++ 11将“ this”作为std :: make_shared的参数传递的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆