STL containers and non copyable (and non movable) objects

后端 未结 2 1170
日久生厌
日久生厌 2021-01-18 03:25

Since STL containers require that all contents be copyable and assignable, what is the prefered idiom when working with non copyable objects?

I can think of two dif

2条回答
  •  夕颜
    夕颜 (楼主)
    2021-01-18 03:39

    I'd choose approach #1: i.e. store smart pointers to objects in STL containers.

    Note that it's fine to store non-owning raw pointers in STL containers (e.g. observing raw pointers), but storing owning raw pointers is a "leaktrocity": use shared_ptr or new C++11's unique_ptr instead.

    As for #2, writing your own containers from scratch requires lots of time and energy, and I believe you can't match the richness of a full commercial-quality STL library implementation in a reasonable time-frame.

提交回复
热议问题