Is calling map::count with an empty weak_ptr as argument safe?

老子叫甜甜 提交于 2019-12-02 17:28:29

问题


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) ){

回答1:


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!