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

后端 未结 10 2038
忘掉有多难
忘掉有多难 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:17

    Generally storing the objects directly in the STL container is best as it is simplest, most efficient, and is easiest for using the object.

    If your object itself has non-copyable syntax or is an abstract base type you will need to store pointers (easiest is to use shared_ptr)

    0 讨论(0)
  • 2020-11-27 10:18

    Using pointers will be more efficient since the containers will be only copying pointers around instead of full objects.

    There's some useful information here about STL containers and smart pointers:

    Why is it wrong to use std::auto_ptr<> with standard containers?

    0 讨论(0)
  • 2020-11-27 10:20

    You seem to have a good grasp of the difference. If the objects are small and easy to copy, then by all means store them.

    If not, I would think about storing smart pointers (not auto_ptr, a ref counting smart pointer) to ones you allocate on the heap. Obviously, if you opt for smart pointers, then you can't store temp stack allocated objects (as you have said).

    @Torbjörn makes a good point about slicing.

    0 讨论(0)
  • 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<boost::shared_ptr<protocol> > 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<protocol> protocols;
    connection c(protocols[0]); // value-semantics, takes a copy of the protocol
    
    0 讨论(0)
提交回复
热议问题