mardi 14 avril 2020

calling function that returns rvalue reference

I think I understand most of the rvalue stuff, but when I tried to implement the following code, I got segmentation fault(core dumped) :( maybe I'm still missing some details and would appreciate any help!

I have this struct Mode in my header:

#include <memory>
#include <iostream>

struct Mode
{
    explicit Mode(const int id_in, const int p_val=1) : id{id_in}, p{new int{p_val}} {
        std::cout << "explicit param default ctr called..." << std::endl;

    }
    Mode() : id{42}, p{nullptr}{
        std::cout << "default ctr called..." << std::endl;
    }

    Mode&& clone() {
        Mode m(*this);
        m.p.reset(new int{*m.p});
        return std::move(m);
    }   
    int id;
    std::shared_ptr<int> p;
};

and in main.cpp I do this:

int main()
{
    Mode m{42, 43};
    Mode m2;
    m2 = m.clone();

    cout << m.p << endl;
    cout << m2.p;
}

what happens in detail in the line m2 = m.clone()? What I understand so far is: in clone() it creates a temporary copy of m using the copy constructor Mode m(*this), and std::move the contents of this temp object, and finally returns to its caller m2. And in main.cpp I assign the rvalue to m2 using move assignment? I'm not so sure till this step...

Aucun commentaire:

Enregistrer un commentaire