C++: returning by reference and copy constructors

后端 未结 9 1798
伪装坚强ぢ
伪装坚强ぢ 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:22

    One potential solution, depending on your use case, is to default-construct the object outside of the function, take in a reference to it, and initialize the referenced object within the function, like so:

    void initFoo(Foo& foo) 
    {
      foo.setN(3);
      foo.setBar("bar");
      // ... etc ...
    }
    
    int main() 
    {
      Foo foo;
      initFoo(foo);
    
      return 0;
    }
    

    Now this of course does not work if it is not possible (or does not make sense) to default-construct a Foo object and then initialize it later. If that is the case, then your only real option to avoid copy-construction is to return a pointer to a heap-allocated object.

    But then think about why you are trying to avoid copy-construction in the first place. Is the "expense" of copy construction really affecting your program, or is this a case of premature optimization?

提交回复
热议问题