为了演示移动语义,我编写了以下示例代码,其中包含 int 的隐式构造函数。
struct C {
int i_=0;
C() {}
C(int i) : i_( i ) {}
C( const C& other) :i_(other.i_) {
std::cout << "A copy construction was made." << i_<<std::endl;
}
C& operator=( const C& other) {
i_= other.i_ ;
std::cout << "A copy assign was made."<< i_<<std::endl;
return *this;
}
C( C&& other ) noexcept :i_( std::move(other.i_)) {
std::cout << "A move construction was made." << i_ << std::endl;
}
C& operator=( C&& other ) noexcept {
i_ = std::move(other.i_);
std::cout << "A move assign was made." << i_ << std::endl;
return *this;
}
};
And
auto vec2 = std::vector<C>{1,2,3,4,5};
cout << "reversing\n";
std::reverse(vec2.begin(),vec2.end());
带输出
A copy construction was made.1
A copy construction was made.2
A copy construction was made.3
A copy construction was made.4
A copy construction was made.5
reversing
A move construction was made.1
A move assign was made.5
A move assign was made.1
A move construction was made.2
A move assign was made.4
A move assign was made.2
现在,背面显示了 2 个两个交换(每个交换使用一个移动分配和两个移动结构),但为什么是临时的C
从初始化列表创建的对象无法移动?我以为我有一个整数的初始值设定项列表,但我现在想知道我之间是否有一个 Cs 的初始值设定项列表,其中can't被移出(作为其常量)。这是正确的解释吗? - 这是怎么回事?
现场演示 http://ideone.com/MQqMGd
我以为我有一个整数的初始值设定项列表,但我现在想知道我之间是否有一个 Cs 的初始值设定项列表,它无法从中移动(作为其常量)。这是正确的解释吗?
这是对的。vector<C>
没有initializer_list<int>
构造函数甚至initializer_list<T>
某些模板参数的构造函数T
。它所拥有的是initializer_list<C>
构造函数 - 它是由您传入的所有整数构建的。由于initializer_list
是一个 const 数组,你会得到一堆副本而不是一堆移动。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)