C返回一个对象副本

我写了以下代码
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 no mutable nonsense happening behind it) and it would not make any copies of the objects and perform these const operations on the private member of the MyObjectHolder 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视为程序员而不是编译器的东西更清楚.

相关文章

本程序的编译和运行环境如下(如果有运行方面的问题欢迎在评...
水了一学期的院选修,万万没想到期末考试还有比较硬核的编程...
补充一下,先前文章末尾给出的下载链接的完整代码含有部分C&...
思路如标题所说采用模N取余法,难点是这个除法过程如何实现。...
本篇博客有更新!!!更新后效果图如下: 文章末尾的完整代码...
刚开始学习模块化程序设计时,估计大家都被形参和实参搞迷糊...