简体   繁体   中英

Return a unique_ptr from a member method of a private member variable

I have the below code where I am trying to return a unique_ptr of a private member variable from a member function:

#include <memory>

class Interface1
{
public:
  virtual ~Interface1() = default;
  virtual void Show() const = 0;
};

class Interface2
{
public:
  virtual ~Interface2() = default;
  virtual std::unique_ptr<Interface1> Interface1Ptr() const = 0;
};

class CInterface1 : public Interface1
{
public:
  CInterface1 (){}
  virtual ~CInterface1() = default;
  virtual void Show() const override
  {
  }
};

class CInterface2 : public Interface2
{   
public:
  CInterface2 ()
  {
    mifi = std::make_unique<CInterface1>();
  }
  virtual ~CInterface2() = default;
  virtual std::unique_ptr<Interface1> Interface1Ptr() const override
  {
    return std::move(mifi);
  }
  private:
   std::unique_ptr<Interface1> mifi;
};

main()
{
    return 0;
}

But I am getting below compile error:

$ c++ -std=c++14 try50.cpp
try50.cpp: In member function 'virtual std::unique_ptr<Interface1> CInterface2::Interface1Ptr() const':
try50.cpp:38:22: error: use of deleted function 'std::unique_ptr<_Tp, _Dp>::unique_ptr(const std::unique_ptr<_Tp, _Dp>&) [with _Tp = Interface1; _Dp = std::default_delete<Interface1>]'
 return std::move(mifi);
                      ^
In file included from C:/tools/mingw64/x86_64-w64-mingw32/include/c++/memory:81:0,
                 from try50.cpp:1:
C:/tools/mingw64/x86_64-w64-mingw32/include/c++/bits/unique_ptr.h:356:7: note: declared here
       unique_ptr(const unique_ptr&) = delete;
       ^

Is it not possible to return the unique_ptr - I am fine if I lose the ownership also?

You've declared the member function const:

 virtual std::unique_ptr<Interface1> Interface1Ptr() const ^ 

Therefore the members are const. You attempt to copy-initialize the returned unique pointer from the const member. Since the member is const, it cannot be moved from (because the argument of the move constructor is non-const) and therefore only copy is possible. But as the error shows, unique pointers are not copyable.

Is it not possible to return the unique_ptr - I am fine if I loose the ownership also?

It is possible to transfer ownership from a member unique pointer... but only in a non-const member function.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM