Polymorphic objects on the stack?

后端 未结 7 672
忘了有多久
忘了有多久 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:34

    Having read it I think the point is (especially given the second sentence about copy-semantics) that universal base class is useless for objects handled by value, so it would naturally lead to more handling via reference and thus more memory allocation overhead (think template vector vs. vector of pointers).

    So I think he meant that the objects would have to be allocated separately from any structure containing them and that it would have lead to many more allocations on heap. As written, the statement is indeed false.

    PS (ad Captain Giraffe's comment): It would indeed be useless to have function

    f(object o)
    

    which means that generic function would have to be

    f(object &o)
    

    And that would mean the object would have to be polymorphic which in turn means it would have to be allocated separately, which would often mean on heap, though it can be on stack. On the other hand now you have:

    template 
    f(T o) // see, no reference
    

    which ends up being more efficient for most cases. This is especially the case of collections, where if all you had was a vector of such base objects (as Java does), you'd have to allocate all the objects separately. Which would be big overhead especially given the poor allocator performance at time C++ was created (Java still has advantage in this because copying garbage collector are more efficient and C++ can't use one).

提交回复
热议问题