简体   繁体   中英

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 ?

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. 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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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