调用map :: count用空的weak_ptr作为参数安全吗? [英] Is calling map::count with an empty weak_ptr as argument safe?

查看:160
本文介绍了调用map :: count用空的weak_ptr作为参数安全吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可以安全地 map :: count 未初始化的空值 weak_ptr 安全?



我仍然没有经验的c ++,没有技巧来确定这个。 p>

在我的应用程序中,一个 weak_ptr 正被保留在地图中的关键字并且必须首先被值找到。如果找不到,未初始化的 weak_ptr return ed,并在 map ::计数



代码



设置

  map< my_ptr,connection_data,owner_less< my_ptr>> m_connections; 
typedef map< my_ptr,connection_data,owner_less< my_ptr>> :: iterator it;

按资料查找

  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;
}

查找

  my_ptr found_ptr = get_my_ptr_from_data(data); 
if(my_ptrs.count(found_ptr)){


解决方案

可以安全地调用 find (和 count ),只要你定义的任何订单都不会t依赖指针是非空的。 找到(和 count )的唯一的事情是使用参数作为比较器的参数。



但是,使用 weak_ptr 作为关联容器中的键是不安全的。如果它过期,那么容器的顺序是破碎的,以后尝试使用容器会给出不明确的行为。


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.

这篇关于调用map :: count用空的weak_ptr作为参数安全吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆