在函数中返回std :: vector时复制了多少数据,将std :: vector放在free-store(在堆上)并返回指针的优化程度是多少,即:
std::vector *f()
{
std::vector *result = new std::vector();
/*
Insert elements into result
*/
return result;
}
Run Code Online (Sandbox Code Playgroud)
效率高于:
std::vector f()
{
std::vector result;
/*
Insert elements into result
*/
return result;
}
Run Code Online (Sandbox Code Playgroud)
?
Visual C++不执行返回值优化吗?
#include <cstdio>
struct Foo { ~Foo() { printf("Destructing...\n"); } };
Foo foo() { return Foo(); }
int main() { foo(); }
Run Code Online (Sandbox Code Playgroud)
我编译并运行它:
cl /O2 test.cpp
test.exe
Run Code Online (Sandbox Code Playgroud)
它打印:
破坏...
破坏......
为什么不执行RVO?
我读了几篇关于如何从方法返回向量的帖子包括以下内容:
我仍然对如何在VS2013中以正确的方式传递向量感到困惑,以及此代码中的以下方法之间的区别(问题在注释中标记):
class Foo{
private:
std::vector<int> vect;
public:
//1 - classic way?
void GetVect(std::vector<int>& v)
{
v = vect;// assignment with swap?
}
//2 - RVO?
std::vector<int> GetVect()
{
return vect;
}
//3 - RVO with const?
std::vector<int> GetVect() const
{
return vect;
}
//4 - just move?
std::vector<int> GetVect()
{
return std::move(vect);
}
//5 - move with {}?
std::vector<int> GetVect()
{
return { std::move(vect) };
}
}
Run Code Online (Sandbox Code Playgroud)
所以我不确定// 1是否是// 2的显式形式,不确定3是否有效.4和5之间有什么区别?如果RVO适用于VS2013中的矢量,如何测试?
#include <iostream>
using namespace std;
struct A
{
A()
{
cout << "A()" << endl;
}
~A()
{
cout << "~A()" << endl;
}
A(A&&)
{
cout << "A(A&&)" << endl;
}
A& operator =(A&&)
{
cout << "A& operator =(A&&)" << endl;
return *this;
}
};
struct B
{
// According to the C++11, the move ctor/assignment operator
// should be implicitly declared and defined. The move ctor
// /assignment operator should implicitly call class A's move
// ctor/assignment …Run Code Online (Sandbox Code Playgroud)