Using unique_ptr with the operator= overload [duplicate]

17 hours ago 1
ARTICLE AD BOX

Consider the following piece of pseudo-code:

class Foo { public: Foo &operator=(const Foo& right) { this->ptr = right.ptr; this->ptr = std::move( right.ptr ); } private: std::unique_ptr<SomeClass> ptr; };

The code above will fail to compile because unique_ptr is not copyable..

I also can't use std::move() as it gives an error with MSVC:

attempt to reference a deleted function

How to properly implement operator=() in this case?

wohlstad's user avatar

wohlstad

37.1k18 gold badges79 silver badges114 bronze badges

Igor's user avatar

4

You're trying to implement the copy assignment operator for something that just isn't copyable. What is the actual and underlying problem you need to solve? It smells like you have a design problem that you try to solve through code, which is most often a bad idea.

2026-02-10 05:39:36 +00:00

Commented 1 hour ago

You have to implement copy and assignment operators and decide how to handle the std::unique_ptr. One option is to clone the object it manages (and create a new std::unique_ptr).

2026-02-10 05:42:51 +00:00

Commented 1 hour ago

@Richard, thank you for the links - they are very helpful. After looking thru them I think I will have to convert to shared_ptr. The reason being that SomeClass is a base class and I will be creating derived pointers on the fly. Thx for those links once again. I'll upvote the comment.

2026-02-10 06:24:55 +00:00

Commented 35 mins ago

Read Entire Article