samedi 21 avril 2018

Is move() with unique_ptr irreplaceable?

I am not sure if the title is even relative as I do not have enough knowledge about move(). For this very reason it was hard to search and successfully find an answer to my question.

consider the following code:

struct A
{
    A(){cout << "Created!\n";}
    ~A(){cout << "Destroyed!\n";};
};

void f()
{
    unique_ptr<A> q(new A);

    unique_ptr<A> t (q.release());  // ----> (1)
    // unique_ptr<A> t = move(q);   // ----> (2) 
}

int main() { f(); }

My understanding is: in both cases (1) and (2) the t will take the A ownership from q without destroying the object A.

  1. Is this correct?
  2. What is the difference between (1) and (2)?

I can see that move() is not part of the unique_ptr, instead it seems to me part of std so it has more general uses.

I am new to C++ and so in the simplest possible way:

  1. What can move do? What are its uses?

Aucun commentaire:

Enregistrer un commentaire