C返回一个对象副本

C返回一个对象副本,第1张

概述我写了以下代码: class MyObjectHolder {public: std::vector<int> getMyObject() const { return myObject; }private: std::vector<int> myObject;}; 在我的程序的某些时候,我尝试使用getMyObject方法并在检索到的对象上仅使用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返回一个对象副本全部内容,希望文章能够帮你解决C返回一个对象副本所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/langs/1256177.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-06-07
下一篇 2022-06-07

发表评论

登录后才能评论

评论列表(0条)

保存