如何返回std :: make_unique< SubClass>工作? [英] How does returning std::make_unique<SubClass> work?
问题描述
我有一个基类及其子类:
I have a base class and its subclass:
class Base {
public:
virtual void hi() {
cout << "hi" << endl;
}
};
class Derived : public Base {
public:
void hi() override {
cout << "derived hi" << endl;
}
};
试图创建一个辅助函数,该函数创建一个派生对象的唯一指针.
Trying to create a helper function that creates a unique pointer of a Derived object.
1)这个有效:
std::unique_ptr<Base> GetDerived() {
return std::make_unique<Derived>();
}
2)但是,这个编译失败:
2) But, this one fails to compile:
std::unique_ptr<Base> GetDerived2() {
auto a = std::make_unique<Derived>();
return a;
}
3)std :: move works:
3) std::move works:
std::unique_ptr<Base> GetDerived3() {
auto a = std::make_unique<Derived>();
return std::move(a);
}
4)如果我创建一个Base实例,则两者都可以工作:
4) If I create a Base instance, both work:
std::unique_ptr<Base> GetDerived4() {
auto a = std::make_unique<Base>();
return a;
}
std::unique_ptr<Base> GetDerived5() {
auto a = std::make_unique<Base>();
return std::move(a);
}
为什么(2)失败,但是其他人可以工作?
Why (2) fails but others work?
推荐答案
std::unique_ptr
是不可复制的,只能移动.您可以从声明为返回std::unique_ptr<Base>
的函数中return std::make_unique<Derived>
的原因是,存在从一个到另一个的转换.
std::unique_ptr
is not copyable, only movable. The reason you can return std::make_unique<Derived>
from a function declared to return std::unique_ptr<Base>
is that there is a conversion from one to the other.
所以1)等效于:
std::unique_ptr<Base> GetDerived() {
return std::unique_ptr<Base>(std::made_unique<Derived>());
}
由于从std::make_unique
返回的值是一个右值,因此返回值是移动构造的.
Since the value returned from std::make_unique
is an rvalue, the return value is move-constructed.
将其与2)进行对比,等效于:
Contrast that to 2), which is equivalent to:
std::unique_ptr<Base> GetDerived2() {
std::unique_ptr<Derived> a = std::make_unique<Derived>();
return std::unique_ptr<Base>(a);
}
由于a
是左值,因此返回值必须是复制构造的,并且std::unique_ptr
是不可复制的.
since a
is an lvalue, the return value must be copy-constructed, and std::unique_ptr
is non-copyable.
3)之所以起作用,是因为将左值a
转换为右值,并且返回值可以移动构造.
3) works because you cast the lvalue a
to an rvalue, and the return value can be move-constructed.
4)和5)之所以起作用,是因为您已经有了一个std::unique_ptr<Base>
并且不需要构造一个来返回.
4) and 5) work because you already have a std::unique_ptr<Base>
and don't need to construct one to return.
这篇关于如何返回std :: make_unique< SubClass>工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!