Returning Large Objects in Functions

后端 未结 9 1210
無奈伤痛
無奈伤痛 2020-11-27 14:17

Compare the following two pieces of code, the first using a reference to a large object, and the second has the large object as the return value. The emphasis on a \"large o

相关标签:
9条回答
  • 2020-11-27 14:56

    Yes in the second case it will make a copy of the object, possibly twice - once to return the value from the function, and again to assign it to the local copy in main. Some compilers will optimize out the second copy, but in general you can assume at least one copy will happen.

    However, you could still use the second approach for clarity even if the data in the object is large without sacrificing performance with the proper use of smart pointers. Check out the suite of smart pointer classes in boost. This way the internal data is only allocated once and never copied, even when the outer object is.

    0 讨论(0)
  • 2020-11-27 14:56

    Alternatively, you can avoid this issue all together by letting the object get its own data, i. e. by making getObjData() a member function of LargeObj. Depending on what you are actually doing, this may be a good way to go.

    0 讨论(0)
  • 2020-11-27 14:59

    Your first snippet is especially useful when you do things like have getObjData() implemented in one DLL, call it from another DLL, and the two DLLs are implemented in different languages or different versions of the compiler for the same language. The reason is because when they are compiled in different compilers they often use different heaps. You must allocate and deallocate memory from within the same heap, else you will corrupt memory. </windows>

    But if you don't do something like that, I would normally simply return a pointer (or smart pointer) to memory your function allocates:

    LargeObj* getObjData()
    {
      LargeObj* ret = new LargeObj;
      ret->fillWithData() ;
      return ret;
    }
    

    ...unless I have a specific reason not to.

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