简体   繁体   English

QSharedPointer作为方法参数或方法的返回值的良好实践?

[英]Good practice for QSharedPointer as method parameter or return value of a method?

Is there any good practice or regulation on how to use a QSharedPointer object as method parameter or return value of a method ? 关于如何使用QSharedPointer对象作为方法参数或方法的返回值,是否有任何良好的做法或规定?

By value: 按价值:

LMNode::setParent(QSharedPointer<LMNode> parent)
{
    this->parent = parent;
}

QSharedPointer<LMNode> LMNode::getParent()
{
    return this->parent;
}

or better by reference: 或参考更好:

LMNode::setParent(const QSharedPointer<LMNode>& parent)
{
    this->parent = parent;
}

const QSharedPointer<LMNode>& LMNode::getParent()
{
    return this->parent;
}

Sure, in the second version i avoid the increment of the reference counter and the changing of the QSharedPointer object. 当然,在第二个版本中,我避免了引用计数器的增量和QSharedPointer对象的更改。 But is there a stringent way how as I have to do? 但是,我必须采取严格的方法吗?

I'd pass it by value . 按值传递它。

You said that in the second option (if you return by reference), you'll "avoid" the increment of the reference counter. 你说在第二个选项中(如果你通过引用返回),你将“避免”引用计数器的增量。 You're right, and that implies that you run the risk of deleting the object when it goes out of scope (in another thread for example). 你是对的,这意味着当它超出范围时(例如在另一个线程中),你冒着删除对象的风险。

And... that would be my only (good) reason. 而且......那将是我唯一的(好)理由。 One could argue that passing by value is costlier, but I'll just let them remember about Want speed? 有人可能会说,通过价值传递是更昂贵的,但我只是让他们记住关于旺动的速度? Pass by value. 通过价值。

Also note that there is a very good answer on how to use smart pointers here . 还要注意的是有关于如何使用智能指针一个很好的答案在这里

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM