Using a new operator to copy an object into a heap without knowing its type

I have a doubt, the function below can get an object of type A or something derived.

A *copyToHeap(A &obj) {
    A *ptr=new A(obj);
    return ptr;
}

If we call it this way:

//B inherits from A
B bObj;
B *hPtr=copyToHeap(bObj);

Does the object pointed hPtrto really have type A or B? Is it safe to do this?

+5
source share
6 answers

when you follow below in your code:

A* ptr = new A(obj);

you always get a copy of A. obj will be considered as A, and a new A will be created based on the "A-part" of obj.

The best approach is as an earlier answer, add a virtual MakeCopy method to the base class and implement it for derived classes.

virtual A* MakeCopy();

, . , , A, B, B "", .

+4

pointer to A, , , hPtr, A. , , B, undefined. , factory.

+5

-

#include <memory>

class Base
{
public:
    virtual std::unique_ptr<Base> Clone() = 0;
};

class Derived : public Base
{
public:
    Derived(int i) : i_(i)
    {

    }

    std::unique_ptr<Base> Clone()
    {
        return std::unique_ptr<Derived>(new Derived(i_));
    }

private:
    int i_;
};


std::unique_ptr<Base> copyToHeap(std::unique_ptr<Base> obj) 
{
    return obj->Clone();
}
+2

, , . g++ -Wall GCC?

+1

:

B *hPtr=copyToHeap(bObj); //error: invalid conversion from ‘A*’ to ‘B*’

hPtr A*, , A. - A A B, A, B.

+1

- , / , ( , ) - , "copyToHeap".

As Lucian points out, you probably need a factory. factory creates your object on the heap to start with (and returns a smart pointer to control the lifetime of the object / pointer / memory).

0
source

All Articles