How to “return an object” in C++?

后端 未结 8 693
礼貌的吻别
礼貌的吻别 2020-11-22 09:25

I know the title sounds familiar as there are many similar questions, but I\'m asking for a different aspect of the problem (I know the difference between having things on t

8条回答
  •  感动是毒
    2020-11-22 09:56

    One quick way to determine if a copy constructor is being called is to add logging to your class's copy constructor:

    MyClass::MyClass(const MyClass &other)
    {
        std::cout << "Copy constructor was called" << std::endl;
    }
    
    MyClass someFunction()
    {
        MyClass dummy;
        return dummy;
    }
    

    Call someFunction; the number of "Copy constructor was called" lines that you will get will vary between 0, 1, and 2. If you get none, then your compiler has optimised the return value out (which it is allowed to do). If you get don't get 0, and your copy constructor is ridiculously expensive, then search for alternative ways to return instances from your functions.

提交回复
热议问题