Re: Passing References: Is this correct and according to standard?
* Akshay Loke:
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)
now in another class, I have:
MFnDagNode parent;
parent.addChild(node.object());
Where node is MfnDependencyNode&
And node.object() returns MObject
This gives me error
?error: no matching function for call to
?MfnDagNode::addChild(Mobject)?
Note: candidates are: Mstatus MFnDagNode::addChild(MObject&, unsigned
int, bool)
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?
Probably it doesn't return a temporary const object. Probably it returns an
object. Which is not const but is an rvalue.
So this is the way I have done this?
const MObject& nodeObjectConstRef = node.object();
MObject& nodeObjectRef = const_cast<MObject&> (nodeObjectConstRef);
parent.addChild(nodeObjectRef);
and This works!
Assuming node.object() returns by value, it's formally UB.
Why don't you do
MObject nodeObject = node.object();
parent.addChild( nodeObject );
?
But also, if this is a graph chances are you need to allocate the objects
dynamically, not as automatic objects.
Initially I tried this,
MObject& nodeObjectConstRef = node.object();
parent.addChild(nodeObjectConstRef );
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??
The first method above is working, but am not sure if I am suppressing
something using the const_cast?
You're suppressing readability and grokkability. But most of all your own
understanding.
Cheers, & hth.,
- Alf
--
A: Because it messes up the order in which people normally read text.
Q: Why is it such a bad thing?
A: Top-posting.
Q: What is the most annoying thing on usenet and in e-mail?