Ada*_*dam 4 c++ shared-ptr c++11
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; }
Run Code Online (Sandbox Code Playgroud)
该function1和function2可以使用和改变FF的某些部分.
我的情况在这里:
我需要使用arg *this或者调用函数shared_from_this().
print(msg, *this);
or
print(msg, this->shared_from_this());
Run Code Online (Sandbox Code Playgroud)
我可以在我的代码中使用function1或function2样式化一个函数.
但是,如果我使用function2样式,我需要实现Foo继承std::enable_shared_from_this,但是有了function1样式,我不需要.
我在单线程环境中使用此功能
你只传递shared_ptr给函数如果函数在乎那里是一个shared_ptr,通常是因为它要保留一份副本,或weak_ptr.
任何其他东西只会降低功能的适用性而无法获得.