简体   繁体   中英

Best practice way to store collection

I am porting a C# application to C++, and I have the following class (where Box is a struct, and the BoxStore will be a global, long living object in the app):

public class BoxStore
{
    private List<Box> boxes;

    ...

    public List<Box> GetBoxes()
    {
        return this.boxes;
    }
}

I'm planning to store the boxes collection in a std::vector in C++. There are multiple ways to define the collection:

std::vector<Box> boxes;
shared_ptr<std::vector<Box>> boxes;
std::vector<Box>& boxes;
(*std::vector<Box> boxes;)

What is - if there is any - best way to go? I guess the last option (to store a raw pointer to the collection) is the worst solution without any benefit (hence the parantheses)).

And what is the best approach to port the GetBoxes method? Of course this depends on the way of storing the collection. I can see multiple approaches here too:

(std::vector<Box> GetBoxes();)
std::shared_ptr<std::vector<Box>> GetBoxes();
*std::vector<Box> GetBoxes();
std::vector<Box>& GetBoxes();

The first solution seems incorrect, because the vector would get copied upon return, thus the caller couldn't modify the original collection.
However the other three approaches seem equally good to me. The BoxStore instance is long living, and is not getting destroyed while the app is running, so the caller won't have ownership over the collection. Does this mean, that returning a shared_ptr is semantically incorrect? (It is always the BoxStore object, who frees the collection.)

And is there a significant difference between returning a raw pointer or a reference?

This could be the possible one you are looking for. BoxStore really owns the objects. So, no pointers etc are needed. I'm assuming that the individual box objects and the list won't outlive the Store. If you have that requirement, then you might need to consider using pointers.

Regarding the return by reference is not really good design since it violates the encapsulation . So, if you didn't have the constraint to allow the clients to modify the list, I would have provided a copy of the list to out.

#include <list>

class Box
{
...
};

class BoxStore
{
private :
    std::list<Box> boxes;

public :
    std::list<Box>& GetBoxes()
    {
        return boxes;
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM