5

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?

demonplus
  • 5,036
  • 11
  • 41
  • 56

1 Answers1

-1

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.

IAmInPLS
  • 3,648
  • 4
  • 22
  • 55
  • Thanks for your comment. Helps to make decisions. About the cost by passing by value, `QSharedPointer` object has the size of two normal pointers, so passing by reference would save 4 or 8 Bytes (depending on system architecture). Dont know, whever this can be an issue. Interesting article. – Ferenc Rozsa Sep 08 '17 at 16:49