Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

Move semantics moves objects, it doesn’t copy them.

For example, if you have a class C containing a pointer P to some data, where C’s destructor frees that pointer:

- a shallow copy of object O would return an object O2, containing that same pointer P, and leave O unmodified.

- a move of O to O2 would (1) make O2 contain P, but also would update O to no longer have that pointer P (it has to make that change, as destructing O at a later time shouldn’t free P anymore)

(1) yes, an implementation could also copy the data or increase a reference count, or, possibly, a zillion different things without running into problems.



Shallow copy is the general concept. Move semantics is a special case where the unique ownership is enforced. Here is simple example of the idea:

  Widget::Widget(Widget&& w) {
    this->ptr = w.ptr; // shallow copy
    w.ptr = nullptr; // nullify the source
  }


You could use;

auto* p2 = std::exchange( p1, nullptr );




Consider applying for YC's Fall 2025 batch! Applications are open till Aug 4

Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: