Search code examples
c++pointersdynamicmove

Should i delete a moved from dynamic pointer


I understand how to move an object, for example:

int a(5), b(6);
int c(std::move(a)); // move constructor
c = std::move(b);    // move assignment

I understand the common implementation of a custom move constructor (which takes the ownership of a dynamic pointer and sets the moved-from pointer to nullptr.)

But I haven't found anything about moving a dynamically allocated pointer itself. I need confirmation that the following code is legal:

int *p(new int(42));
int val(std::move(*p));
delete p; // I think this is no longer necessary. Is it?

So, is it allowed to move a dynamic pointer?


Solution

  • std::move does not move anything. It merely casts an l-value reference to an r-value reference.

    In the example you give, the pointer p has not moved anywhere.

    BTW. please don't deal in raw pointers - use a std::unique_ptr instead.

    This allocates memory for an int, initialises the int to the value of 42 and stores the address of that memory in p.

    int *p(new int(42));
    

    This casts the int pointed to by p to an int&& and then constructs the int val from that r-value reference. Since int is an integral type, a construction from an r-value (i.e. a move) is equivalent to a copy (this is mandated in the standard)

    int val(std::move(*p));
    

    Yes, this is still necessary.

    delete p;// i think this is no longer necessary. is it ?