Returning *this in member functions

后端 未结 9 1290
无人共我
无人共我 2020-12-18 22:35

I recently used a library that allows the following type of syntax:

MyClass myObject;
myObject
    .setMember1(\"string value\")
    .setMember2(4.0f)
    .s         


        
9条回答
  •  生来不讨喜
    2020-12-18 23:16

    In theory, you could end up with a dangling reference if you do something awful like:

    MyClass *myObject = new MyClass;
    MyClass & dangling = myObject->setMember1("string");
    delete myObject;
    dangling.setMember2(yrParam);
    

    So be aware of that.

提交回复
热议问题