Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 492
Cevik Avatar asked Feb 28 '26 13:02

Cevik


2 Answers

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 ?
like image 159
Richard Hodges Avatar answered Mar 03 '26 02:03

Richard Hodges


In your second example, your code essentially copy the value of one integer to anther. You are not moving the pointer, you are moving the integer the pointer points to.

int a = 42;
int b = std::move(a);

std::cout << a << " : " << b << std::endl; // prints 42 : 42

Moving an integer is copying them.

Even if you moved the pointer, the value of the pointer of copied:

int* a = new int{42};
int* b = std::move(a);

std::cout << *a << " : " << *b << std::endl; // prints 42 : 42
std::cout << std::boolalpha << (a == b) << std::endl; // prints true

So moving raw pointers are copying them too. You will still need to delete the p pointer.

For every new, there's a delete.

If you don't want to delete it yourself, consider std::unique_ptr, which is aware about move semantics.

Built-in type such as raw pointer, int, floats are not aware of move semantics and moving them will simply copying them.

like image 22
Guillaume Racicot Avatar answered Mar 03 '26 02:03

Guillaume Racicot