I wrote the following code:
class MyObjectHolder {
public:
std::vector<int> getMyObject() const {
return myObject;
}
private:
std::vector<int> myObject;
};
At some point of my program I attempt to use the getMyObject method and use only const methods on the retrieved object:
const std::vector<int> myObject = myObjectHolder.getMyObject();
myObject.size();
int a = myObject.front();
Now, is it possible that the compiler will optimize this code so that no copies of the
std::vector<int>are done?Is it somehow possible that the compiler determines that I'm only using the
constmethods on the retrieved object (and let's assume there is nomutablenonsense happening behind it) and it would not make any copies of the objects and perform theseconstoperations on theprivatemember of theMyObjectHolderinstead?If yes, would it be possible if I didn't explicitly declare the
const std::vector<int> myObjectasconst?If no, what are the reasons not to do this? In which cases this optimization would be to hard to implement / deduce that it's possible and correct here / etc... ?