如果我有一个需要使用a的函数shared_ptr,那么传递它的引用会不会更有效(所以为了避免复制shared_ptr对象)?有哪些可能的不良副作用?我设想了两种可能的情况:
1)在函数内部,复制由参数组成,如
ClassA::take_copy_of_sp(boost::shared_ptr<foo> &sp)
{
...
m_sp_member=sp; //This will copy the object, incrementing refcount
...
}
Run Code Online (Sandbox Code Playgroud)
2)在函数内部仅使用参数,例如
Class::only_work_with_sp(boost::shared_ptr<foo> &sp) //Again, no copy here
{
...
sp->do_something();
...
}
Run Code Online (Sandbox Code Playgroud)
我无法在两种情况下都看到传递boost::shared_ptr<foo>by值而不是引用的充分理由.按值传递只会"暂时"增加由于复制而引用的引用计数,然后在退出函数范围时减少它.我忽略了什么吗?
只是为了澄清,在阅读了几个答案之后:我完全赞同过早优化的问题,而且我总是试着先在热点上进行首次剖析.如果你知道我的意思,我的问题更多来自纯粹的技术代码观点.
将shared_ptr派生类型传递给采用shared_ptr基类型的函数的最佳方法是什么?
我通常通过shared_ptr引用传递s以避免不必要的副本:
int foo(const shared_ptr<bar>& ptr);
Run Code Online (Sandbox Code Playgroud)
但如果我尝试做类似的事情,这不起作用
int foo(const shared_ptr<Base>& ptr);
...
shared_ptr<Derived> bar = make_shared<Derived>();
foo(bar);
Run Code Online (Sandbox Code Playgroud)
我可以用
foo(dynamic_pointer_cast<Base, Derived>(bar));
Run Code Online (Sandbox Code Playgroud)
但这似乎是次优的,原因有两个:
dynamic_cast对于简单的派生到基础演员来说,A 似乎有点过分.dynamic_pointer_cast创建一个指向传递给函数的副本(虽然是临时的).有更好的解决方案吗?
原来这是一个缺少头文件的问题.此外,我在这里尝试做的是一个反模式.通常,
不影响对象生命周期的函数(即对象在函数持续时间内保持有效)应采用普通引用或指针,例如int foo(bar& b).
使用对象的函数(即,是给定对象的最终用户)应该采用unique_ptrby值,例如int foo(unique_ptr<bar> b).std::move调用者应该将值放入函数中.
延长对象生命周期的函数应采用shared_ptrby值,例如int foo(shared_ptr<bar> b).避免循环引用的通常建议适用.
有关详细信息,请参阅Herb Sutter的回归基础讲座.
关于如何使用QSharedPointer对象作为方法参数或方法的返回值,是否有任何良好的实践或规则?
按价值:
LMNode::setParent(QSharedPointer<LMNode> parent)
{
this->parent = parent;
}
QSharedPointer<LMNode> LMNode::getParent()
{
return this->parent;
}
Run Code Online (Sandbox Code Playgroud)
或参考更好:
LMNode::setParent(const QSharedPointer<LMNode>& parent)
{
this->parent = parent;
}
const QSharedPointer<LMNode>& LMNode::getParent()
{
return this->parent;
}
Run Code Online (Sandbox Code Playgroud)
当然,在第二个版本中,我避免了参考计数器的增量和QSharedPointer对象的变化.但是,我必须采取严格的方法吗?
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样式,我不需要.
我在单线程环境中使用此功能
如果函数Foo()将所有权转移std::unique_ptr到函数Bar()并且说Bar()抛出异常,则包含的对象std::unique_ptr将被销毁.
Foo()在这种情况下,如何处理可能希望保留所有权的案例.
class A
{
public:
std::unique_ptr<SomeData> getSomeData(...);
};
class B
{
public:
pushToQ(std::unique_ptr<SomeData>);
doSomething()
...
popFromQ();
...
};
Run Code Online (Sandbox Code Playgroud)
现在,如果B::pushToQ()抛出,QueueFullException我将丢失getSomeData()我可能不想要的数据.