Re: Passing References: Is this correct and according to standard?
Akshay Loke <firstname.lastname@example.org> wrote:
I have this function from a class MFnDagNode,
addChild( MObject & child, unsigned int index = kNextPos, bool
keepExistingParents = false );
which takes an object reference as first input parameter (ignore the
rest since those are default)
Because 'child' is a *non-const* reference, the only objects that it can
refer to are l-values.
now in another class, I have:
Where node is MfnDependencyNode&
And node.object() returns MObject
This gives me error
?error: no matching function for call to
Note: candidates are: Mstatus MFnDagNode::addChild(MObject&, unsigned
Now I am not sure why this doesn?t work and the object doesn?t get
implicitly cast to the MObject& reference argument, but I am assuming
that could be because the node.object() returns a temporary const
object and it cannot be cast to a MObject& reference?
Correct, but even if node.object() returned a temporary *non-const*
object, it still wouldn't work.
So this is the way I have done this?
const MObject& nodeObjectConstRef = node.object();
MObject& nodeObjectRef = const_cast<MObject&> (nodeObjectConstRef);
and This works!
Your unlucky, it's undefined behavior.
Initially I tried this,
MObject& nodeObjectConstRef = node.object();
but that didn?t work ? it gives the error,
?error: invalid initialization of non-const reference of type
?MObject&? from a temporary of type ?MObject??
Right, a non-const reference can only refer to an l-value.
The first method above is working, but am not sure if I am suppressing
something using the const_cast?
Better to do this:
MObject obj = node.object(); // makes a modifiable copy of the return
addChild( obj );
My guess though is that even this won't really work. I suspect that
'addChild' keeps a pointer to the object passed in and unless you are
very careful, obj is going out of scope before the pointer to it does.