C++: Vector of objects vs. vector of pointers to new objects?

前端 未结 4 1410
遥遥无期
遥遥无期 2020-12-13 00:33

I am seeking to improve my C++ skills by writing a sample software renderer. It takes objects consisting of points in a 3d space and maps them to a 2d viewport and draws cir

4条回答
  •  天命终不由人
    2020-12-13 01:26

    As for your first question, it is generally preferred to use automatically allocated objects rather than dynamically allocated objects (in other words, not to store pointers) so long as for the type in question, copy-construction and assignment is possible and not prohibitively expensive.

    If the objects can't be copied or assigned, then you can't put them directly into a std::vector anyway, and so the question is moot. If the copying and/or assignment operations are expensive (e.g. the object stores a large amount of data), then you might want to store pointers for efficiency reasons. Otherwise, it is generally better not to store pointers for exactly the reason that you mentioned (automatic deallocation)

    As for your second question, yes, that is another valid reason to store pointers. Dynamic dispatch (virtual method calls) work only on pointers and references (and you can't store references in a std::vector). If you need to store objects of multiple polymorphic types in the same vector, you must store pointers in order to avoid slicing.

提交回复
热议问题