class MyObjectHolder { public: std::vector<int> getMyObject() const { return myObject; } private: std::vector<int> myObject; };
在我的程序的某些时候,我尝试使用getMyObject方法并在检索到的对象上仅使用const方法:
const std::vector<int> myObject = myObjectHolder.getMyObject(); myObject.size(); int a = myObject.front();
>现在,编译器是否可能优化此代码,以便没有std :: vector< int>的副本.完成?
Is it somehow possible that the compiler determines that I’m only using the
const
methods on the retrieved object (and let’s assume there is nomutable
nonsense happening behind it) and it would not make any copies of the objects and perform theseconst
operations on theprivate
member of theMyObjectHolder
instead?
>如果是,如果我没有明确声明const std :: vector< int> myObject as const?
>如果不是,不这样做的原因是什么?在这种情况下,这种优化将难以实现/推断它可能并在这里更正/等…?
解决方法
Now,is it possible that the compiler will optimize this code so that no copies of the
std::vector<int>
are done?
不,编译器不知道调用者将对该对象做什么,除非您对使用该对象的所有代码使用全局优化(编译器通常不能对其使用进行假设;此外,如果对象是从dll它根本不能做出任何假设.
If yes,would it be possible if I didn’t explicitly declare the const std::vector myObject as const?
不,无论如何,从非const到const的转换可能是隐含的.
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… ?
这是一个应该在getMyObject()内完成的optmiziation,但编译器不能确定调用者不会抛弃const.实际上这是关于const的使用的一个非常古老的争论,通常我认为总是将const视为程序员而不是编译器的东西更清楚.