c++ - 关于 shared_ptr 用法的问题 - C++

标签 c++ smart-pointers shared-ptr

我对使用 shared_ptr 的最佳实践有几个问题。

问题 1

复制 shared_ptr 便宜吗?还是我需要将它作为对我自己的辅助函数的引用并作为值返回?类似的,

void init_fields(boost::shared_ptr<foo>& /*p_foo*/);
void init_other_fields(boost::shared_ptr<foo>& /*p_foo*/);

boost::shared_ptr<foo> create_foo()
{
    boost::shared_ptr<foo> p_foo(new foo);
    init_fields(p_foo);
    init_other_fields(p_foo);
}

问题 2

我应该使用 boost::make_shared 来构造 shared_ptr 吗?如果是,它提供了哪些优势?当 T 没有无参数构造函数时,我们如何使用 make_shared

问题 3

如何使用const foo*?我找到了两种方法来做到这一点。

void take_const_foo(const foo* pfoo)
{

}

int main()
{
    boost::shared_ptr<foo> pfoo(new foo);
    take_const_foo(pfoo.get());
    return 0;
}

typedef boost::shared_ptr<foo> p_foo;
typedef const boost::shared_ptr<const foo> const_p_foo;

void take_const_foo(const_p_foo pfoo)
{

}

int main()
{
     boost::shared_ptr<foo> pfoo(new foo);
     take_const_foo(pfoo);
     return 0;
}

问题 4

如何返回并检查 shared_ptr 对象上的 NULL?是不是有点像,

boost::shared_ptr<foo> get_foo()
{
     boost::shared_ptr<foo> null_foo;
     return null_foo;
}

int main()
{
     boost::shared_ptr<foo> f = get_foo();
     if(f == NULL)
     {
          /* .. */
     }
     return 0;
}

任何帮助都会很棒。

最佳答案

大部分问题都已得到解答,但我不同意 shared_ptr 拷贝很便宜。

拷贝与传递引用具有不同的语义。它将修改引用计数,这将在最好的情况下触发原子增量,在最坏的情况下触发锁定。 你必须决定你需要什么语义,然后你就会知道是通过引用传递还是通过值传递。

从性能的角度来看,使用 boost 指针容器而不是 shared_ptr 容器通常是一个更好的主意。

关于c++ - 关于 shared_ptr 用法的问题 - C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2144814/

相关文章:

c++ - VC++调试器调用类成员函数

c++ - shared_ptr 类中 get() 成员的用途是什么?

c++ - 应该一直使用 boost::ptr_vector 代替 std::vector 吗?

c++ - 成员函数定义

c++ - 找不到CoreAudio,AudioToolbox,AudioUnit等 header

c++ - 如何按值传递仅 move 类型(例如 std::unique_ptr)?

c++ - "single allocation"对 boost::make_shared 意味着什么

c++ - 是否有与 shared_from_this 等效的 weak_ptr?

c++ - 在 Visual Studio 2008 中使用 Boost 1.40.0 的 boost::shared_ptr 的 Intellisense 失败

C++。 valgrind 输出 : Syscall param open(filename) points to unaddressable byte(s)