Polymorphic objects on the stack?

后端 未结 7 671
忘了有多久
忘了有多久 2021-02-01 02:53

In Why is there no base class in C++?, I quoted Stroustrup on why a common Object class for all classes is problematic in c++. In that quote there is the statement:

7条回答
  •  挽巷
    挽巷 (楼主)
    2021-02-01 03:44

    I think Bjarne means that obj, or more precisely the object it points to, can't easily be stack-based in this code:

    int f(int arg) 
    { 
        std::unique_ptr obj;    
        switch (arg) 
        { 
        case 1:  obj = std::make_unique(); break; 
        case 2:  obj = std::make_unique(); break; 
        default: obj = std::make_unique(); break; 
        } 
        return obj->GetValue(); 
    }
    

    You can't have an object on the stack which changes its class, or is initially unsure what exact class it belongs to.

    (Of course, to be really pedantic, one could allocate the object on the stack by using placement-new on an alloca-allocated space. The fact that there are complicated workarounds is beside the point here, though.)

    The following code also doesn't work as might be expected:

    int f(int arg) 
    { 
        Base obj = DerivedFactory(arg); // copy (return by value)
        return obj.GetValue();
    }
    

    This code contains an object slicing error: The stack space for obj is only as large as an instance of class Base; when DerivedFactory returns an object of a derived class which has some additional members, they will not be copied into obj which renders obj invalid and unusable as a derived object (and quite possibly even unusable as a base object.)

    Summing up, there is a class of polymorphic behaviour that cannot be achieved with stack objects in any straightforward way.


    Of course any completely constructed derived object, wherever it is stored, can act as a base object, and therefore act polymorphically. This simply follows from the is-a relationship that objects of inherited classes have with their base class.

提交回复
热议问题