我有这段代码:
#include <iostream>
#include <vector>
using namespace std;
class Foo{
public:
Foo() noexcept {cout << "ctor" << endl;}
Foo(const Foo&) noexcept {cout << "copy ctor" << endl;}
Foo(Foo&&) noexcept {cout << "move ctor" << endl;}
Foo& operator=(Foo&&) noexcept {cout << "move assn" << endl; return *this;}
Foo& operator=(const Foo&) noexcept {cout << "copy assn" << endl; return *this;}
~Foo() noexcept {cout << "dtor" << endl;}
};
int main()
{
Foo foo;
vector<Foo> v;
v.push_back(std::move(foo));
// comment the above 2 lines and replace by
// vector<Foo> v{std::move(foo)};
}
输出是我所期望的(用 编译g++ -std=c++11 --no-elide-constructors
,没有标志的相同输出)
ctor
move ctor
dtor
dtor
现在而不是push_back
直接使用初始化向量v
作为
vector<Foo> v{std::move(foo)};
我不明白为什么我得到输出:
1) (没有--no-elide-constructors
)
ctor
move ctor
copy ctor
dtor
dtor
dtor
2) (带--no-elide-constructors
)
ctor
move ctor
move ctor
copy ctor
dtor
dtor
dtor
dtor
在第一种情况下,为什么要调用复制 ctor?在第二种情况下,当编译器不执行省略时,我完全不知道为什么调用了 move ctor 两次。有任何想法吗?