Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

vector, move semantics, nothrow and g++ 4.7

I wrote the following code to understand move semantics. It works as expected (ie. no copies and only moves) in g++-4.6 but not in g++-4.7.0. I thought that is a bug in linking in g++-4.7.0 but this link says that it is not a bug in g++-4.7. So, as understood by me from the above link, I made the move constructor nothrow but still it does only copies. However, if I make the copy constructor nothrow, only moves take places. Can any one explain this?

#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;
}
like image 752
suresh Avatar asked Apr 20 '12 06:04

suresh


1 Answers

How are you "making the move constructor nothrow"? With g++ 4.7, if I annotate the move constructor with noexcept then your example does only moves:

S(S&& x) noexcept{ ... }

no of moves = 25
no of copies = 0
like image 105
Anthony Williams Avatar answered Oct 23 '22 18:10

Anthony Williams