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

后端 未结 8 536
礼貌的吻别
礼貌的吻别 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.

    0 讨论(0)
  • 2020-11-22 09:59

    I don't want to return a copied value because it's inefficient

    Prove it.

    Look up RVO and NRVO, and in C++0x move-semantics. In most cases in C++03, an out parameter is just a good way to make your code ugly, and in C++0x you'd actually be hurting yourself by using an out parameter.

    Just write clean code, return by value. If performance is a problem, profile it (stop guessing), and find what you can do to fix it. It likely won't be returning things from functions.


    That said, if you're dead set on writing like that, you'd probably want to do the out parameter. It avoids dynamic memory allocation, which is safer and generally faster. It does require you have some way to construct the object prior to calling the function, which doesn't always make sense for all objects.

    If you want to use dynamic allocation, the least that can be done is put it in a smart pointer. (This should be done all the time anyway) Then you don't worry about deleting anything, things are exception-safe, etc. The only problem is it's likely slower than returning by value anyway!

    0 讨论(0)
提交回复
热议问题