从一个私有成员变量的成员方法返回一个unique_ptr

3

以下是一段代码,我想通过一个成员函数返回一个私有成员变量的unique_ptr:

#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;
}

但是我遇到了以下编译错误:
$ 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;
       ^

是否无法返回unique_ptr - 如果我失去所有权,我也没关系吗?


8
转移对象内包含指针的所有权意味着修改对象的状态。您的函数被标记为“const”,这意味着它不能修改对象的状态。 - milleniumbug
此外,在返回语句中,您不需要使用std::move,请参见返回值优化。 - Vladimir Berezkin
2
@VladimirBerezkin 在这里绝对需要使用 std::move。但仅此是不够的。当返回成员数据时,无法应用 RVO。 - eerorika
unique_ptr默认情况下确保对象在没有所有权时将被删除,而我不能使用shared_ptr - 所有权将由某个对象拥有。 - Programmer
1
@程序员 - 你可以阅读这本Andrei Alexandrescu现代C++设计 - Victor Gubin
显示剩余5条评论
1个回答

10

您已经将成员函数声明为const:

virtual std::unique_ptr<Interface1> Interface1Ptr() const
                                                    ^
因此,成员是const。您试图从const成员复制初始化返回的独特指针。由于成员是const,因此无法移动它(因为移动构造函数的参数是非const),因此只能进行复制。但是,正如错误显示的那样,唯一指针不可复制。
“不返回unique_ptr也可以吗,如果我失去所有权我没关系。”
可以从非const成员函数中转移成员unique指针的所有权。

@程序员 你也应该明白,一旦调用CInterface2::Interface1Ptr()完成,CInterface2::mifi将不再有有效的指针。 - shargors

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接