Should I store entire objects, or pointers to objects in containers?

后端 未结 10 2072
忘掉有多难
忘掉有多难 2020-11-27 09:31

Designing a new system from scratch. I\'ll be using the STL to store lists and maps of certain long-live objects.

Question: Should I ensure my objects have copy co

10条回答
  •  再見小時候
    2020-11-27 10:20

    If the objects are to be referred to elsewhere in the code, store in a vector of boost::shared_ptr. This ensures that pointers to the object will remain valid if you resize the vector.

    Ie:

    std::vector > protocols;
    ...
    connection c(protocols[0].get()); // pointer to protocol stays valid even if resized
    

    If noone else stores pointers to the objects, or the list doesn't grow and shrink, just store as plain-old objects:

    std::vector protocols;
    connection c(protocols[0]); // value-semantics, takes a copy of the protocol
    

提交回复
热议问题