本文介绍了这会复制载体吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有以下代码,是否复制了矢量?

If I have the following code, is the vector copied?

std::vector<int> x = y.getTheVector();

还是取决于getTheVector()的返回类型是否是引用?

or would it depend on whether the return type of getTheVector() is by reference?

或者我只需要使用:

std::vector<int>& x = y.getTheVector();

或者,我需要两者都做吗?

or, would I need to do both?

推荐答案

std::vector<int> x = y.getTheVector();

不管y.getTheVector();的返回类型如何,

始终进行复制.

always makes a copy, regardless of the return type of y.getTheVector();.

std::vector<int>& x = y.getTheVector();

不会复制.但是,只要y.getTheVector()返回对该函数返回后将是有效的对象的引用,则x将有效.如果y.getTheVector()返回在函数中创建的对象,则x将指向在语句后不再有效的对象.

would not make a copy. However, x will be valid as long as y.getTheVector() returns a reference to an object that is going to be valid after the function returns. If y.getTheVector() returns an object created in the function, x will point to an object that is no longer valid after the statement.

这篇关于这会复制载体吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-12 02:04