C ++ returns a copy of an object

I wrote the following code:

class MyObjectHolder { public: std::vector<int> getMyObject() const { return myObject; } private: std::vector<int> myObject; }; 

At some point in my program, I try to use the getMyObject method and use only the const methods on the extracted object:

 const std::vector<int> myObject = myObjectHolder.getMyObject(); myObject.size(); int a = myObject.front(); 
  • Now, is it possible that the compiler optimizes this code so that there is no copy of std::vector<int> ?

    It is somehow possible that the compiler determines that I only use const methods on the extracted object (and suppose there is no mutable behind it), and it would not make any copies of the objects and perform these const operations on the private MyObjectHolder instead ?

  • If so, would it be possible if I did not explicitly declare const std::vector<int> myObject as const ?

  • If not, what are the reasons for not doing this? In what cases will this optimization be difficult to implement / infer that this is possible and fix here / etc ...?

+6
source share
3 answers

Now, is it possible that the compiler will optimize this code so that copies of std::vector<int> not executed?

No, the compiler does not know what calls this object will make if you do not use global optimization throughout the code that uses this object (the compiler cannot make any assumptions about its use at all, moreover, if the object is exported from dll, it does not can make no assumptions whatsoever).

If so, is it possible if I did not explicitly declare const std :: vector myObject as const?

No, in any case, the conversion from non-constant to const may be implicit.

If not, what are the reasons for not doing this? In what cases will this optimization be difficult to implement / infer that this is possible and fix here / etc ...?

This is an optmiziation that must be done inside getMyObject() , but the compiler cannot be sure that callers will not cast const. These are actually very old discussions about using const , usually I think itโ€™s more clear to always think of const as something for programmers, not compilers.

+6
source

I would suggest using

 const std::vector<int>& getMyObject() const { return myObject; } 

It will return the permalink myObject without copying.

And use the result with

 const std::vector<int>& myObject = myObjectHolder.getMyObject(); 
+3
source

It is possible to Copy Elision and Optimization of the return value will be used. If you use a C ++ compiler with support for C ++ 11 , you can optimize it by moving semantics .

Would I recommend reading the excellent Want Speed article ? Pass by Value by Dave Abrahams with a discussion in the comments below.

However, for more information, you should refer to the documentation of your C ++ compiler.

0
source

Source: https://habr.com/ru/post/917018/


All Articles