多态性是否适用于值?或者在按(基)值返回时使用派生 class 的移动构造函数

Does polymorphism apply on values? Or using move constructor of derived class when returning by (base-)value

我正在构建某种工厂方法,通过以下方式 return 将 DerivedClass 作为 BaseClass

BaseClass Factory() 
{
    return DerivedClass();
}

我说得对吗,当我调用该方法时使用了 BaseClass 的移动构造函数:

BaseClass object = Factory();

因为我无法创建BaseClass virtual 的移动构造函数,是否有其他方法强制采用DerivedClass 的移动构造函数?

Edit1:附加信息 - 我已经考虑过指针。但问题是,我想在 DLL 中导出工厂函数,并且我想让它对用户来说尽可能简单。标准指针可能导致内存泄漏,另一方面,并​​不是每个人都熟悉智能指针。

Edit2:据我所知,真正的问题是:多态性是否也适用于 return 按值?
答案是否定的。

我认为你不会这样做:

BaseClass Factory() 

而是

// You'll need to delete
BaseClass* Factory() {
    return new Derived();
}

// You will not need to delete
unique_ptr<BaseClass> Factory() {
    // return new Derived();
    // As the comments point out: prefer use of make_unique
    return std::make_unique<Derived>();
}

否则,你就是slicing你的对象。

Polymorphism works only in pointers and references.

在 C++ 中,您不会 return 派生对象作为基础 class 对象。这看起来像 c# 方式。你应该使用指针。

我假设这是你想要的。

BaseClass* Factory() 
{
    return new DerivedClass();
}

我也没听说过'move constructor'的概念。

C++ 中基本 class 的普通变量、字段、return 类型等不能包含子class 的值。这与 Java 等其他面向对象的语言不同,它与对象在内存中的实际表示方式有关——存储多态值需要指针或引用。 (在 Java 和类似的语言中,所有包含对象的变量实际上都是指向对象的指针,对象本身存储在别处,因此这个实现细节对程序员是隐藏的。)

解决办法是使用一个指针来允许你使用多态性。这个的天真的版本是使函数 return BaseClass *,并将 return 表达式更改为 new DerivedClass(),但是这会使您很容易出现内存泄漏错误,因为您必须手动确保对象在不再需要时被调用者销毁(通过 delete 运算符)。一个更好的解决方案是使用 std::shared_ptr<BaseClass>std::unique<BaseClass> 作为 return 类型,这将确保当对它的引用不再存在时对象被销毁。