问题描述
为什么读取std :: map的成员不被视为const?例如:
class My_Class
{
int Get_Map_Value(int index)const // **错误**未考虑
const !!!
{
返回m_Map [index]; //注意m_Map没有改变,只读
来自
}
std :: map< int,int> m_Map;
};
如果尝试将const用于其预期目的,这真的是一团糟......
[== Peteroid ==]
PS - 我正在使用MS VC ++ .NET并创建一个托管C ++应用程序,如果那样
事情......
如果地图中没有该关键字,map :: operator []将创建一个
新(K,V)对并将其存储在地图中,通过引用返回V部分。
(使用此运算符要求mapped_type是默认构造的。)
您可以通过使用map :: find来避免此行为,尽管您的函数如上面指定的
要么必须返回默认值,要么抛出
异常,如果该函数返回end()。
-
Doug Harrison
Microsoft MVP - Visual C ++
如果密钥是'n'地图中已经存在,map :: operator []将创建一个新的(K,V)对并将其存储在地图中,通过引用返回V部分。
(使用此运算符要求mapped_type是默认构造的。)
你可以通过使用map :: find来避免这种行为,尽管你上面指定的函数要么必须返回默认值,要么抛出如果该函数返回end(),则会出现异常。
-
Doug Harrison
Microsoft MVP - Visual C ++
const是C ++中的堕胎。 />
从理论上讲,这听起来是个好主意。在实践中,它只是不起作用。
Why does reading a member of a std::map not considered const? For example:
class My_Class
{
int Get_Map_Value( int index ) const // ** error ** not considered
const!!!
{
return m_Map[index] ; // note that m_Map is not changed, only read
from
}
std::map<int,int> m_Map ;
} ;
This really reeks havoc when to try to use const for its intended purpose...
[==Peteroid==]
PS - I''m using MS VC++.NET and creating a Managed C++ application, if that
matters...
If the key isn''t already present in the map, map::operator[] will create a
new (K,V) pair and store it in the map, returning the V part by reference.
(Use of this operator requires the mapped_type be default-constructible.)
You can avoid this behavior by using map::find, though your function as
specified above will either have to return a default value or throw an
exception if that function returns end().
--
Doug Harrison
Microsoft MVP - Visual C++
If the key isn''t already present in the map, map::operator[] will create a
new (K,V) pair and store it in the map, returning the V part by reference.
(Use of this operator requires the mapped_type be default-constructible.)
You can avoid this behavior by using map::find, though your function as
specified above will either have to return a default value or throw an
exception if that function returns end().
--
Doug Harrison
Microsoft MVP - Visual C++
const is an abortion in C++.
In theory, it sounds like a good idea. In practice, it just doesn''t work.
这篇关于为什么从std :: map读取不被视为const?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!