Good practice for QSharedPointer as a method parameter or method return value?

Is there any good practice or rule on how to use the QSharedPointer object as a method parameter or method return value?

By value:

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

or better at the link:

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

Of course, in the second version, I avoid incrementing the reference count and changing the QSharedPointer object. But is there a strict way how should I do?

+5
source share
1 answer

I would pass it by value .

You said that in the second option (if you return by reference) you will “avoid” the increment of the reference count. You are right, and this means that you risk deleting the object when it goes out of scope (for example, in another thread).

And ... that will be my only (good) reason. It can be argued that the cost transition is more expensive, but I’ll just let them remember about Want speed? Scroll by value.

Also note that there is a very good answer on how to use smart pointers here .

0
source

Source: https://habr.com/ru/post/1271614/


All Articles