문제

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.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top