[英]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: 我有以下代码,我试图从成员函数返回一个私有成员变量的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;
}
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? 是不是可以返回unique_ptr - 如果我也失去了所有权,我也没事?
You've declared the member function const: 你已经声明了成员函数const:
virtual std::unique_ptr<Interface1> Interface1Ptr() const ^
Therefore the members are const. 因此成员是const。 You attempt to copy-initialize the returned unique pointer from the const member.
您尝试从const成员复制初始化返回的唯一指针。 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.
由于成员是const,因此无法移动(因为移动构造函数的参数是非const),因此只能复制。 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?
是不是可以返回unique_ptr - 如果我还失去了所有权,我也没事?
It is possible to transfer ownership from a member unique pointer... but only in a non-const member function. 可以从成员唯一指针转移所有权......但仅限于非const成员函数。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.