Regarding an unordered_map with the following declaration:

typedef struct
{
    unsigned int length;
    unsigned type;
    std::string data;
} packet;

boost::unordered::unordered_map<int, packet> map;

When I add an object to this map, the unordered_map will clone this object and append it to its container. So my question is it better to have a pointer to the struct instead of adding it as an object?

And if I have a raw pointer as the value in the unordered_map, is there any method I should follow to keep the object alive in the memory and its place not used by other variable even if I get out of the function scope?

有帮助吗?

解决方案

You should use std::unordered_map and its emplace member function, if you wish to avoid the copy.

Don't store pointers, in general: you may slightly speed up some of your code, but if that was even a bottleneck, the trade-off is more complicated code and the increased risk of bugs. Plus lots of dereferences you don't need.

But feel free to profile all three options if you reckon you need to.

其他提示

If you choose to store pointers, you have to allocate your objects on the heap to keep the objects alive when you leave scope. Then you should probably make your container to hold smart pointers (std::unique_ptr ?) instead of raw pointer.

As already mentioned use emplace to avoid copy if your container contains objets.

The problem with storing pointers in any container is that you need to manually manage the life time of the objects stored in the container. That is, if you do the following, the destructor of the container will not automatically free up the dynamically allocated memory.

boost::unordered::unordered_map<int, packet *> map;
map.insert(std::make_pair(1, new packet()));

To resolve this problem you could do the following.

boost::unordered::unordered_map<int, std::shared_ptr<packet>> map;
map.insert(std::make_pair(1, std::make_shared<packet>()));

Note: The code will need additional work to compile.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top