Return private unique_ptr to public member function

Consider the following class prototype:

class ObjHandler {

    std::unique_ptr<Obj> GetPtr() { return obj; }

  private:
    std::unique_ptr<Obj> obj;
};

This generates a compile-time error saying that the copy constructor std::unique_ptrhas been deleted. Why is semantics moving not applied here? Is this due to the fact that it GetPtr()does not have a pointer obj? How do I implement my code (I need a member function that returns a pointer to a stream pointer with minimal overhead)?

+4
source share
2 answers

Why aren't moving semantics applied here?

Because it is objnot a local variable, therefore, the language does not allow them to move implicitly.

, std::move:

std::unique_ptr<Obj> GetPtr() { return std::move(obj); }

, , , , , (.. this->obj ), . MovePtr.

GetPtr , this->obj , .. :

Obj* GetPtr() const { return obj.get(); }
+7

unique " ". , , .

, , , , :

class ObjHandler {
   Object &get(){ return *obj; }
   Object *GetPtr() { return obj.get(); }
private:
   unique_ptr<Object> obj;
};

- , // .

CppCoreGuidelines : , .

+7

Source: https://habr.com/ru/post/1672048/


All Articles