在下面的代码中,如果存在复制构造函数,为什么移动构造函数不会被向量实现调用?我知道它可以调用移动构造函数,因为如果没有复制构造函数它会这样做:
#include <iostream>
#include <vector>
class Cls1 {
public:
Cls1() { std::cout << "default ctor\n"; } // default constructor
Cls1(Cls1&&) { std::cout << "move ctor\n"; } // move constructor
};
class Cls2 {
public:
Cls2() { std::cout << "default ctor\n"; } // default constructor
Cls2(Cls2 const&) { std::cout << "copy ctor\n"; } // copy constructor
Cls2(Cls2&&) { std::cout << "move ctor\n"; } // move constructor
};
template<typename T>
void test(T t1) {
std::vector<T> v;
std::cout << "First push:\n";
v.push_back(std::move(t1));
std::cout << "\nSecond push:\n";
v.push_back(std::move(t1));
std::cout << "\nThird push:\n";
v.push_back(std::move(t1));
std::cout << "\nresize:\n";
v.reserve(100);
std::cout << "\n\n";
}
int main() {
std::cout << "Cls1 - no copy constructor\n";
Cls1 a;
test(std::move(a));
std::cout << "Cls1 - with copy constructor\n";
Cls2 b;
test(std::move(b));
return 0;
}
您可以在此处看到:http://cpp.sh/7wlo
我得到的最新版本的clang和gcc(使用mingw)以及上面链接的站点上的任何编译器的输出显示,对于Cls2
,无论何时必须调整大小,向量都会使用复制构造函数它的内部缓冲区因此错过了优化移动的机会。对于所有级别的优化都是如此。
以下是运行上述代码的示例输出。我注意到&#34;错误&#34;行:
Cls1 - no copy constructor
default ctor
move ctor
First push:
move ctor
Second push:
move ctor
move ctor
Third push:
move ctor
move ctor
move ctor
resize:
move ctor
move ctor
move ctor
Cls1 - with copy constructor
default ctor
move ctor
First push:
move ctor
Second push:
move ctor
copy ctor <--
Third push:
move ctor
copy ctor <--
copy ctor <--
resize:
copy ctor <--
copy ctor <--
copy ctor <--
注意: VS2015实际上似乎做对了。