How come a non-const reference cannot bind to a temporary object?

前端 未结 11 1835
长情又很酷
长情又很酷 2020-11-21 05:19

Why is it not allowed to get non-const reference to a temporary object, which function getx() returns? Clearly, this is prohibited by C++ Standard but I am in

11条回答
  •  囚心锁ツ
    2020-11-21 05:40

    I have a scenario I would like to share where I wish I could do what Alexey is asking. In a Maya C++ plugin, I have to do the following shenanigan in order to get a value into a node attribute:

    MFnDoubleArrayData myArrayData;
    MObject myArrayObj = myArrayData.create(myArray);   
    MPlug myPlug = myNode.findPlug(attributeName);
    myPlug.setValue(myArrayObj);
    

    This is tedious to write, so I wrote the following helper functions:

    MPlug operator | (MFnDependencyNode& node, MObject& attribute){
        MStatus status;
        MPlug returnValue = node.findPlug(attribute, &status);
        return returnValue;
    }
    
    void operator << (MPlug& plug, MDoubleArray& doubleArray){
        MStatus status;
        MFnDoubleArrayData doubleArrayData;
        MObject doubleArrayObject = doubleArrayData.create(doubleArray, &status);
        status = plug.setValue(doubleArrayObject);
    }
    

    And now I can write the code from the beginning of the post as:

    (myNode | attributeName) << myArray;
    

    The problem is it doesn't compile outside of Visual C++, because it's trying to bind the temporary variable returned from the | operator to the MPlug reference of the << operator. I would like it to be a reference because this code is called many times and I'd rather not have MPlug being copied so much. I only need the temporary object to live until the end of the second function.

    Well, this is my scenario. Just thought I'd show an example where one would like to do what Alexey describe. I welcome all critiques and suggestions!

    Thanks.

提交回复
热议问题