将std :: shared_ptr传递给构造函数 [英] Passing std::shared_ptr to Constructors

查看:291
本文介绍了将std :: shared_ptr传递给构造函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在创建Stuff并赋予Foo所有权方面,以下合理而有效的方法是吗?

  class Foo 
{
显式Foo(const std :: shared_ptr< Stuff>& myStuff)
:m_myStuff(myStuff)
{
}

...

私人:
const std :: shared_ptr< Stuff> m_myStuff;
}

std :: shared_ptr< Stuff> foosStuff(new Stuff());
Foo f(foosStuff);


解决方案

因为您对效率感兴趣,所以我想指出两点:



shared_ptr<>是许多标准库类型之一,移动构造比复制构造便宜。复制构造shared_ptr的速度较慢,因为复制需要原子地递增引用计数器,而移动shared_ptr完全不需要触摸引用的数据或计数器。来自文章 要速度吗?按值传递!< Dave Abrahams的 / a>可以了解到,在某些情况下,按值取一个函数参数实际上是有益的。这是其中一种情况:

 类Foo 
{
显式Foo(std :: shared_ptr< Stuff> myStuff)
:m_myStuff(move(myStuff))
{}

...

private:
std :: shared_ptr< Stuff> m_myStuff;
};

现在您可以写

  Foo f(std :: make_shared< Stuff>()); 

其中参数是临时的,并且不会复制shared_ptr(仅移动一次或两次)。 / p>

在此处使用std :: make_shared的优点是仅完成一次分配。在您的情况下,您自己分配了Stuff对象,shared_ptr构造函数还必须动态分配引用计数器和删除器。 make_shared只需一次分配即可为您完成所有工作。


Is the following a reasonable and efficient approach with regard to creating Stuff and giving Foo ownership of it?

class Foo
{
    explicit Foo(const std::shared_ptr<Stuff>& myStuff)
        : m_myStuff(myStuff)
    {
    }

    ...

private:
    const std::shared_ptr<Stuff> m_myStuff;
}

std::shared_ptr<Stuff> foosStuff(new Stuff());
Foo f(foosStuff);

解决方案

Since you are interested in efficiency I'd like to make two points:

shared_ptr<> is one of many standard library types where a move construction is cheaper than a copy construction. Copy constructing shared_ptr is a slower since copying requires the reference counters to be incremented atomically whereas moving a shared_ptr doesn't require touching the referenced data or counters at all. From the article "Want Speed? Pass by value!" by Dave Abrahams one can learn that in certain situations it is actually beneficial to take a function parameter by value. This is one of these cases:

class Foo
{
  explicit Foo(std::shared_ptr<Stuff> myStuff)
  : m_myStuff(move(myStuff))
  {}

  ...

private:
  std::shared_ptr<Stuff> m_myStuff;
};

Now you can write

Foo f (std::make_shared<Stuff>());

where the argument is a temporary and no shared_ptr is ever copied (just moved once or twice).

The use of std::make_shared here has the advantage that only one allocation is done. In your case you allocated the Stuff object by yourself and the shared_ptr constructor had to allocate the reference counters and deleter dynamically as well. make_shared does it all for you with just a single allocation.

这篇关于将std :: shared_ptr传递给构造函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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