向量、移动语义、Nothrow 和 G++ 4.7

vector, move semantics, nothrow and g++ 4.7

本文关键字:G++ Nothrow 移动 语义 向量      更新时间:2023-10-16

我编写了以下代码来理解移动语义。它在 g++-4.6 中按预期工作(即没有副本,只有移动),但在 g++-4.7.0 中则不然。我认为这是 g++-4.7.0 中链接中的一个错误,但这个链接说它不是 g++-4.7 中的错误。因此,正如我从上面的链接中了解到的那样,我制作了移动构造函数 nothrow,但它仍然只复制。但是,如果我使复制构造函数 nothrow,则只会发生移动。谁能解释一下?

#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;
}

你如何"使移动构造函数 nothrow"?在 g++ 4.7 中,如果我用 noexcept 注释移动构造函数,那么您的示例只会移动:

S(S&& x) noexcept{ ... }
no of moves = 25
no of copies = 0