简体   繁体   English

在没有动态内存分配的情况下,C ++中是否有一种机制可以从基类指针生成派生类的完整副本?

[英]Is there a mechanism in C++ to make a full copy of a derived class from a base class pointer without dynamic memory allocation?

Consider the following example, where object slicing occurs during dereference of a base pointer. 请考虑以下示例,其中在取消引用基指针期间发生对象切片。

#include <stdio.h>

class Base {
  public:
    virtual void hello() {
        printf("hello world from base\n");
    }
};
class Derived : public Base{
  public:
    virtual void hello() {
        printf("hello world from derived\n");
    }
};

int main(){
    Base * ptrToDerived = new Derived;
    auto d = *ptrToDerived;
    d.hello();
}

I want the variable d to hold an object of type Derived instead of an object of type Base , without dynamic memory allocation, and without an explicit cast. 我希望变量d保存Derived类型的对象而不是Base类型的对象,没有动态内存分配,也没有显式强制转换。

I have already looked at this question , but the solution proposed in the answer requires dynamic memory allocation, because it returns a pointer to the new object, instead of the value of the new object. 我已经看过这个问题了 ,但是答案中提出的解决方案需要动态内存分配,因为它返回一个指向新对象的指针,而不是新对象的值。

Is this possible in C++11? 这在C ++ 11中是否可行?

No, it's not possible, because if d does not have dynamic storage duration, then it must have static, thread, or automatic storage duration, and in all of those cases, the type of the object is known at compile time. 不,这是不可能的,因为如果d没有动态存储持续时间,那么它必须具有静态,线程或自动存储持续时间,并且在所有这些情况下,对象的类型在编译时是已知的。 In your case, you want the type of the object to be determined at runtime, since ptrToDerived may point to a Base object or a Derived object or to an object of some other class derived from Base . 在您的情况下,您希望在运行时确定对象的类型,因为ptrToDerived可能指向Base对象或Derived对象或从Base派生的某个其他类的对象。

If your concern is about lifetime and memory leaks, just have clone return a std::unique_ptr<Base> instead of Base* . 如果您关注的是生命周期和内存泄漏,请让clone返回std::unique_ptr<Base>而不是Base*

I guess you mean that you want auto to deduce to D . 我想你的意思是你想要auto演绎到D

However this is not possible: all types must be known at compile-time. 但是这是不可能的:所有类型必须在编译时知道。 Imagine if the code were: 想象一下,如果代码是:

Base *b = some_func();
auto d = *b;

There's no way the compiler can know the dynamic type of what b points to, because it might not be decided until runtime. 编译器无法知道b指向的动态类型,因为它可能直到运行时才会被确定。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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