std:: shared pointer and container like std::vector

How to use shared pointer with container:
  • Use it as normal, except
  • When insert or push it to a container, using:
    • push_back(std::move(p))

Shared pointer is a feature that is included in C++ 11. Using shared pointer is great, but it has some problems with standard container like vector, map or queue in std.

The problem is that when we push a shared pointer to a container, the references counter of the shared pointer does increase, but when the container is out of scope, the counter does not decrease. It make the memory leak, as the shared pointer can not be released.

The solution is to use: std::move

Be note that the shared pointer that is moved will be invalid. You need to get it back or insert it to container at the end of function.

No comments:

Post a Comment