【发布时间】:2014-01-30 14:31:13
【问题描述】:
Stackoverflow 上的大多数问题都是关于 shared_ptr 应该通过 ref 或 value 传递。但是我的问题是这样的:
class Foo;
void function1(Foo & ff) { ff.m_abc = 1024; }
void function2(const std::shared_ptr<Foo> & ff) { ff->m_abc = 1024; }
function1 和 function2 可以使用和更改 ff 的某些部分。
我的情况:
我需要使用 arg *this 或 shared_from_this() 调用函数。
print(msg, *this);
or
print(msg, this->shared_from_this());
我可以在我的代码中为函数使用function1 或function2 样式。
但是,如果我使用function2风格,我需要实现Foo来继承std::enable_shared_from_this,但是使用function1风格,我不需要。
我在单线程环境中使用这个函数
【问题讨论】:
-
我不确定我在这里看到了问题。
-
请务必在需要确保引用计数不为零的地方传递值。
-
要么我是,另外,通过shared_ptr,意味着你需要检查nullptr。
-
我假设 some 其他对象已经有一个
shared_ptr到this?在这种情况下,print(msg, *(this->shared_from_this()))使function1的行为与function2相同,假设function2不复制shared_ptr -
不,Foo 类现在不继承自 std::enable_shared_from_this。如果我使用
function2方法,我必须添加这个继承。
标签: c++ c++11 shared-ptr