samedi 4 février 2017

What copy function is called when function is passing value to another?

I have same output when function printData takes object and when it takes rvalue refernce. Even when i disable optimalisation with flag -O0. What copy mechanism cpp use to pass object from return statement?

#include <iostream>

using namespace std;

class MetaData
{
public:
    MetaData (int size, const std::string& name)
            : _name( name )
            , _size( size )
    {
        cout << "normal constr\n";
    }

    // copy constructor
    MetaData (const MetaData& other)
            : _name( std::move(other._name) )
            , _size( std::move(other._size))
    {
        cout << " cp constr" << endl;
    }

    // move constructor
    MetaData (MetaData&& other)
            : _name( other._name )
            , _size( other._size )
    {
        cout << "mv csrt\n";
    }

    MetaData& operator=(const MetaData& other)
    {
        _size = other._size;
        _name = other._name;

        std::cout << "copy assigned\n";
        return *this;
    }
    MetaData& operator=(MetaData&& other)
    {
        _name = std::move(other._name);
        _size = std::move(other._size);
        std::cout << "move assigned\n";
        return *this;
    }

    friend ostream & operator <<(ostream & out, const MetaData & data){
        out << data._name << " " << data._size << endl;
        return out;
    }

    std::string getName () const { return _name; }
    int getSize () const { return _size; }
private:
    std::string _name;
    int _size;
};

MetaData  getData(){
    return MetaData(1, "test");
}

void printData(MetaData data){
    cout << data;
}

int main(){
    printData(getData());

}

My out:

normal constr
test 1

Aucun commentaire:

Enregistrer un commentaire