Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

rvalue as initialiser to construct an object

Tags:

c++

I am new to programming. sorry for my bad english. I have tried to use rvalue as initialiser to initial objects. So, according to the code, it would print out what are the used constructor and assignment operator. But turned out object "what2" and "what3", those don't print out anything. here is the code:

#include <iostream>
using namespace std;
class X{
public:
    int x;
    X()= default;
    X(int num):x{num}{}
    X(const X& y){
        x = y.x;
        std::cout << "copy constructor" << std::endl;
        std::cout << x << std::endl;

    }
    X& operator=(const X& d){
        x = d.x;
        std::cout << "copy assignment" << std::endl;
        return *this;
    }
    X(X&& y){
        x = y.x;
        std::cout << "move constructor" << std::endl;
    }
    X& operator=(X&& b){
        x = b.x;
        std::cout << "move assignment" << std::endl;
        return *this;
    }
};

X operator +(const X& a,const X& b){
    X tmp{};
    tmp.x = a.x +b.x;
    return tmp;
}

int main(int argc, const char * argv[]) {
    X a{7} , b{11};
    X what1;
    cout << "---------------" << endl;
    what1 = a+b;
    cout << "---------------" << endl;
    X what2{a+b};
    cout << "---------------" << endl;
    X what3 = a+b;
    cout << "---------------" << endl;
    std::cout << what1.x << std::endl;
    std::cout << what2.x << std:: endl;
    std::cout <<what3.x << std::endl;
    return 0;
}

the output is:

---------------
move assignment
---------------
---------------
---------------
18
18
18
Program ended with exit code: 0

only "what1" uses assignment properly. so, how can i use rvalue to initial an object? and using operator= to initial an object? thank you very much.

like image 391
Carl Hung Avatar asked Jan 05 '16 15:01

Carl Hung


1 Answers

Your code could result in move operations being used, but your compiler has chosen to elide those moves and allocate the return of operator+ directly at the call site. You can see this happening if you disable copy elision in your compiler (-fno-elide-constructors in GCC or Clang).

Your move constructor and assignment operator will be successfully used in contexts in which copy elision is not permitted, such as this:

X what2 { std::move(what1) }; //can't elide copy, move constructor used
like image 75
TartanLlama Avatar answered Nov 05 '22 11:11

TartanLlama