STL: Stores references or values?

前端 未结 2 2131
悲哀的现实
悲哀的现实 2021-02-07 22:15

I\'ve always been a bit confused about how STL containers (vector, list, map...) store values. Do they store references to the values I pass in, or do they copy/copy construct +

2条回答
  •  自闭症患者
    2021-02-07 22:22

    That depends on your type. If it's a simple value type, and cheap to copy, then storing values is probably the answer. On the other hand, if it's a reference type, or expensive to copy, you'd better store a smart pointer (not auto_ptr, since its special copy semantics prevent it from being stored in a container. Go for a shared_ptr). With a plain pointer you're risking memory leakage and access to freed memory, while with references you're risking the latter. A smart pointer avoids both.

提交回复
热议问题