When should I use a vector of objects instead of a vector of pointers?

前端 未结 4 829
野趣味
野趣味 2021-01-04 08:17

I have a collection of polymorphic objects, all derived from my Animal class: Cat, Dog, and MonkeyFish.

My usual mode of operation is to store these objects in a vec

4条回答
  •  时光取名叫无心
    2021-01-04 08:29

    If you ever hear the argument but it'll be so costly to copy them structures all the time when you want to use full objects instead of pointers in a vector, then your 2 main arguments are:

    1. We don't need to worry about the lifetime issues of the pointers, which means no leaks from that particular code (unless, of course, the structures themselves have pointer data, but that's another story).
    2. The data locality of adjacent structures in memory will boost performance in typical usage scenarios, not slow things down like pointer indirection would (relatively speaking).

    The added cost of copying is normally taken when adding stuff to the container, not when using the data - think a bit about it: what do you do most? add items or use them?

    However, when adding polymorphical objects, the pointers are necessary to avoid slicing.

提交回复
热议问题