Why apply a non-exist key to map::find would return a iterator with first value map size in C++?
std::map<long long, std::shared_ptr<B>> A::b();
You are returning the map
by value, so each time you call a->b()
you create a new copy of the map b_
which is why this kind of comparison:
a->b().find(3) != a->b().end()
...is undefined behavior since each call to b()
returns a different map and comparing iterators from different container is undefined behavior.
Change your declaration (and definition) to return a (const
-)reference:
const std::map<long long, std::shared_ptr<B>>& A::b();
Your function A::b()
returns the map by value. That means a copy is returned, a unique copy each time it is called, and whose iterators are not compatible with the iterators from any other copy.
Return by reference instead.