use*_*112 3 c++ pointers reference vector
如果我有以下代码,是否复制了向量?
std::vector<int> x = y.getTheVector();
Run Code Online (Sandbox Code Playgroud)
或者它取决于返回类型getTheVector()是否通过引用?
或者我只需要使用:
std::vector<int>& x = y.getTheVector();
Run Code Online (Sandbox Code Playgroud)
或者,我需要两个都做吗?
std::vector<int> x = y.getTheVector();
Run Code Online (Sandbox Code Playgroud)
无论返回类型如何,总是复制y.getTheVector();.
std::vector<int>& x = y.getTheVector();
Run Code Online (Sandbox Code Playgroud)
不会复制.但是,x只要y.getTheVector()返回对函数返回后有效的对象的引用,它就会有效.如果y.getTheVector()返回在函数中创建的对象,x则将指向在语句后不再有效的对象.