Is it safe to call map::count on an uninitialized thus empty weak_ptr safe?
I'm still very inexperienced with c++ and do not have the skills to determine this.
In my application, a weak_ptr is being held as key in a map and must be found first by the values. If it cannot be found, an uninitialized weak_ptr is returned and used in map::count.
Code
Setup
map<my_ptr, connection_data, owner_less<my_ptr>> m_connections;
typedef map<my_ptr, connection_data, owner_less<my_ptr>>::iterator it;
Find by data
my_ptr get_my_ptr_from_data(string data){
my_ptr my_ptr_to_send;
for(it iterator = my_ptrs.begin(); iterator != my_ptrs.end(); iterator++) {
if(iterator->second.data == data){
my_ptr_to_send = iterator->first;
break;
}
}
return my_ptr_to_send;
}
Finding
my_ptr found_ptr = get_my_ptr_from_data(data);
if(my_ptrs.count(found_ptr) ){
It's safe to call find (and count), as long as whatever ordering you've defined doesn't rely on the pointer being non-empty. The only thing that find (and count) will do with the argument is use it as an argument for the comparator.
However, it's not safe to use weak_ptr as a key in an associative container. If it expires, then the container's order is broken, and trying to use the container afterwards will give undefined behaviour.
来源:https://stackoverflow.com/questions/23156079/is-calling-mapcount-with-an-empty-weak-ptr-as-argument-safe