使用std :: map< K,V>其中V没有可用的默认构造函数 [英] Using std::map<K,V> where V has no usable default constructor

查看:327
本文介绍了使用std :: map< K,V>其中V没有可用的默认构造函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个符号表实现为 std :: map 。对于该值,没有办法通过默认构造函数合法地构造值类型的实例。但是如果我不提供默认的构造函数,我得到一个编译器错误,如果我使构造函数assert,我的程序编译只是罚款,但崩溃内 map< K,V> :: operator [ 如果我尝试使用它来添加一个新成员。

I have a symbol table implemented as a std::map. For the value, there is no way to legitimately construct an instance of the value type via a default constructor. However if I don't provide a default constructor, I get a compiler error and if I make the constructor assert, my program compile just fine but crashes inside of map<K,V>::operator [] if I try to use it to add a new member.

有一种方法,我可以让C ++禁止 map [k] 作为编译时的l值(同时允许它作为r值)

Is there a way I can get C++ to disallow map[k] as an l-value at compile time (while allowing it as an r-value)?


BTW:我知道我可以使用 Map.insert(map< K,V> :: value_type (k,v))

BTW: I know I can insert into the map using Map.insert(map<K,V>::value_type(k,v)).


编辑:有几个人提出了解决方案,这意味着更改值的类型,以便地图可以构造一个而不调用默认构造函数。 这与我想要的结果完全相反,因为它会隐藏错误,直到稍后。如果我愿意这样做,我可以简单地从构造函数中删除断言。我想要的是让错误发生更快;在编译时。但是,似乎没有办法区分r值和l值使用 operator [] 所以看起来我想要的不能做,所以我

several people have proposed solution that amount to altering the type of the value so that the map can construct one without calling the default constructor. This has exactly the opposite result of what I want because it hides the error until later. If I were willing to have that, I could simply remove the assert from the constructor. What I Want is to make the error happen even sooner; at compile time. However, it seems that there is no way to distinguish between r-value and l-value uses of operator[] so it seems what I want can't be done so I'll just have to dispense with using it all together.

推荐答案

您不能让编译器区分两种使用方式operator [],因为他们是一样的东西。操作符[]返回一个引用,所以赋值版本只是分配给该引用。

You can't make the compiler differentiate between the two uses of operator[], because they are the same thing. Operator[] returns a reference, so the assignment version is just assigning to that reference.

就个人而言,我从不使用operator []码。请使用insert()和find()。注意,make_pair()函数使insert更容易使用:

Personally, I never use operator[] for maps for anything but quick and dirty demo code. Use insert() and find() instead. Note that the make_pair() function makes insert easier to use:

m.insert( make_pair( k, v ) );






在C ++ 11中,


In C++11, you can also do

m.emplace( k, v );
m.emplace( piecewise_construct, make_tuple(k), make_tuple(the_constructor_arg_of_v) );

这篇关于使用std :: map&lt; K,V&gt;其中V没有可用的默认构造函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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