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.
source share