Hacker News new | past | comments | ask | show | jobs | submit login

Move semantics is the language support for shallow copies. If you never use shallow copies, fine! But a lot of code bases use shallow copies, and it's a valuable tool.



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 );


No, you do shallow copies by using pointers or references. No move required.


Who owns the pointer or reference and what, if anything, enforces that?




Consider applying for YC's Spring batch! Applications are open till Feb 11.

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

Search: