Good practice for QSharedPointer as method parameter or return value of a method?
Asked Answered
A

1

6

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?

Assistance answered 7/9, 2017 at 16:7 Comment(0)
C
-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.

Comitia answered 8/9, 2017 at 13:50 Comment(1)
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.Incredulity

© 2022 - 2024 — McMap. All rights reserved.