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

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

问题描述

我有一个符号表实现为 std :: map 。对于该值,无法通过默认构造函数合法构造值类型的实例。但是,如果我没有提供一个默认的构造函数,我会得到一个编译器错误,如果我使构造函数assert,我的程序编译很好,但是在$ code> 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))插入到地图中/ code>。

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

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

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.

推荐答案

你不能使编译器区分两种用途运算符[],因为它们是一样的。运算符[]返回一个引用,所以赋值版本只是分配给该引用。

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()函数使插入更容易使用:

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

即使未提供复制/移动构造函数。

even if the copy/move constructor is not supplied.

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

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