我写了下面的代码来理解移动语义。它按照预期工作(即。在g++-4.6中没有拷贝,只有移动),但在g++-4.7.0中没有。我认为这是g++-4.7.0中链接的错误,但这个link显示它不是g++-4.7中的错误。因此,正如我从上面的链接中理解的那样,我创建了move构造函数nothrow,但它仍然只复制。但是,如果我将复制构造函数设为nothrow,则只有moves发生。有人能解释这一点吗?
#include <iostream>
#include <vector>
using namespace std;
struct S{
int v;
static int ccount, mcount;
S(){}
//no throw constructor
//S(nothrow)(const S & x){
S(const S & x){
v = x.v;
S::ccount++;
}
S(S&& x){
v = x.v;
S::mcount++;
}
};
int S::ccount = 0;
int S::mcount = 0;
int main(){
vector<S> v;
S s;
for(int i = 0; i < 10; i++) {
v.push_back(std::move(s));
}
cout << "no of moves = " << s.mcount << endl;
cout << "no of copies = " << s.ccount << endl;
return 0;
}发布于 2012-04-20 14:34:05
你是如何“让移动构造器nothrow”的?在g++ 4.7中,如果我用noexcept注释move构造函数,那么您的示例只做moves:
S(S&& x) noexcept{ ... }
no of moves = 25
no of copies = 0https://stackoverflow.com/questions/10241182
复制相似问题