简体   繁体   中英

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.

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?

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. 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 .

If your concern is about lifetime and memory leaks, just have clone return a std::unique_ptr<Base> instead of Base* .

I guess you mean that you want auto to deduce to 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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