mardi 24 mars 2015

C++ 11 Move Semantics

I'm trying to understand how C++ 11 move semantics works. I have implemented a class which wraps a pointer to a String object but neither the move constructor nor the move assignment operator are being called as expected.


I'm using GCC 4.7.2 through Eclipse CDT:


Could you help me understand the reason?



#include <iostream>
#include <string>
#include <utility>

using namespace std;

class StringPointerWrapper {
public:

// Default constructor with default value
StringPointerWrapper(const std::string& s = "Empty"): ps(new std::string(s)) {
std::cout << "Default constructor: " << *ps << std::endl;
}

//Copy constructor
StringPointerWrapper(const StringPointerWrapper& other): ps(new std::string(*other.ps)) {
std::cout << "Copy constructor: " << *other.ps << std::endl;
}

//Copy assignment operator
StringPointerWrapper& operator=(StringPointerWrapper other) {
std::cout << "Assignment operator (ref): " << *other.ps << std::endl;
swap(ps, other.ps);
return *this;
}


//Alternate copy assignment operator
/*StringPointerWrapper& operator=(StringPointerWrapper& other) {
std::cout << "Assignment operator (val)" << std::endl;
//We need to do the copy by ourself
StringPointerWrapper temp(other);
swap(ps, temp.ps);
return *this;
}*/

//Move constructor
StringPointerWrapper(StringPointerWrapper&& other) noexcept : ps(nullptr) {
std::cout << "Move constructor: " << *other.ps << std::endl;
ps = other.ps;
other.ps = nullptr;
}

//Move assignment operator
StringPointerWrapper& operator= (StringPointerWrapper&& other) noexcept {
std::cout << "Move assignment operator: " << *other.ps << std::endl;
if(this != &other) {
delete ps;
ps = other.ps;
other.ps = nullptr;
}
return *this;
}


//Destructor
~StringPointerWrapper() {
std::cout << "Destroying: " << *this << std::endl;
delete ps;
}
private:
friend std::ostream& operator<<(std::ostream& os, StringPointerWrapper& spw) {
os << *spw.ps;
return os;
}
std::string *ps;
};


int main(int argc, char *argv[]) {

StringPointerWrapper spw1("This is a string");
StringPointerWrapper spw2;
StringPointerWrapper spw3("This is another string");
StringPointerWrapper spw4 = {"This is a const string"};
StringPointerWrapper spw5(StringPointerWrapper("String for move constructor"));
std::cout << "spw2 before: " << spw2 << std::endl;
spw2 = spw3;
std::cout << "spw2 after: " << spw2 << std::endl;
StringPointerWrapper spw6 = StringPointerWrapper("String for move assignment");
std::cout << spw1 << std::endl;
std::cout << spw2 << std::endl;
std::cout << spw3 << std::endl;
std::cout << spw4 << std::endl;
std::cout << spw5 << std::endl;
std::cout << spw6 << std::endl;
}

Aucun commentaire:

Enregistrer un commentaire