C++: returning by reference and copy constructors

后端 未结 9 1818
伪装坚强ぢ
伪装坚强ぢ 2020-12-09 09:46

References in C++ are baffling me. :)

The basic idea is that I\'m trying to return an object from a function. I\'d like to do it without returning a pointer (because

9条回答
  •  南笙
    南笙 (楼主)
    2020-12-09 10:15

    You are stucked with either:

    1) returning a pointer

    MyClass* func(){ //some stuf return new MyClass(a,b,c); }

    2) returning a copy of the object MyClass func(){ return MyClass(a,b,c); }

    Returning a reference is not valid because the object is to be destroyed after exiting the func scope, except if the function is a member of the class and the reference is from a variable that is member of the class.

提交回复
热议问题