【发布时间】:2017-06-13 05:05:41
【问题描述】:
为了演示移动语义,我编写了以下示例代码,其中包含来自 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;
}
};
还有
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 的初始化列表,不能从中移动(作为它的常量)。这是一个正确的解释吗? - 怎么回事?
【问题讨论】:
-
很确定 this 是您遇到的问题。
-
@NathanOliver,这是关于从 C 的初始化列表中移动,但我认为我有一个整数列表,用于构建临时 C 对象。
-
std::vector<C>类型的向量需要std::initializer_list<C>,因此您的 int 列表被构造为 C 的临时列表,并且正是从中复制的 C 列表。至少这是我认为代码必须要做的事情。 -
初始化器列表构造对非聚合进行复制。就是这样,对不起。
-
std::vector<C>没有采用std::initializer_list<int>的构造函数(但它有一个用于std::initializer_list<C>的构造函数)。
标签: c++ c++14 move-semantics initializer-list