1

Say I have an object a of type A.

If I want to move this to a function foo(A).

One option is to do foo(std::move(a)), which will invoke the move constructor.

But, let's say I am using a class over which I don't have control. If I still want to move the type, won't this suffice?

std::unique_ptr<A> a_ptr(new A());
foo(std::move(a_ptr));

with foo changed to accepting a unique_ptr.

Aren't the two similar (with the small overhead of using a smart pointer in the second case)?

BusyProgrammer
  • 2,783
  • 5
  • 18
  • 31
ksb
  • 670
  • 8
  • 19
  • 3
    The overhead is dynamic allocation. – Guillaume Racicot Apr 21 '17 at 22:51
  • Possible duplicate: [What are move semantics?](http://stackoverflow.com/q/3106110/734069) – Nicol Bolas Apr 21 '17 at 22:58
  • The 1st case moves the object, the 2nd case moves the smart pointer. – Richard Critten Apr 21 '17 at 23:24
  • if your compiler support C++14, not use raw 'new' operator, use std::make_unique is better(Said Herb Sutter, ISO c++ Spring 2013 meeting)! – Brent81 Apr 22 '17 at 03:34
  • Yeah so the overhead is dynamic allocation + a small overhead of a unique ptr. But the end result is the same right? I managed to avoid copying the object A, correct? – ksb Apr 22 '17 at 03:54
  • It is not clear to me what you want achieve. Do you want to transfer ownership of something, or just avoid copying? For the latter, just pass by reference, for the first please illustrate what you intend to do. – chtz Apr 22 '17 at 08:01
  • Avoid copying. Passing by reference would lead to a copy if I were to store the object through foo() somehow. – ksb Apr 22 '17 at 11:52

1 Answers1

-1

No, with this syntax you're moving the unique pointer, not the object. The object must support being moved. But since you're ok with using the pointer, avoid moving and pass the pointer. The overhead is a single pointer indirection (very small).

trollkill
  • 44
  • 3
  • Yeah I know that the pointer is being moved. But the underlying object is not copied right? So isn't the end result the same? – ksb Apr 22 '17 at 03:51