Re: Using non-const predicate in std::map fails to compile in release
On Mon, 6 Oct 2008 07:27:02 -0700, ??MS?parport IOCTL
<MSparportIOCTL@discussions.microsoft.com> wrote:
#include <iostream>
#include <functional>
#include <map>
#include <cassert>
#include <tchar.h>
using namespace std;
int _tmain(int argc, _TCHAR* argv[])
{
struct c_wstring_compare
: std::binary_function<const wchar_t *, const wchar_t *, bool>
{
inline result_type
operator()(first_argument_type left, second_argument_type right)
{
return wcscmp(left, right) < 0;
}
};
typedef map<const wchar_t *, const wchar_t *, c_wstring_compare>
MyCharMap;
MyCharMap container;
container.find(_T("key2"));
return 0;
}
The code above can be compiled successfully in debug mode while fails in
release mode (visual studio 2008).
The error message is:
E:\Microsoft Visual Studio 9.0\VC\include\xtree(1268) : error C3848:
expression having type 'const wmain::c_wstring_compare' would lose some
const-volatile qualifiers in order to call 'bool
wmain::c_wstring_compare::operator ()(const wchar_t *,const wchar_t *)'
Should it be regarded as a defect?
First, it shouldn't depend on debug vs release, and second, it shouldn't
care whether or not the predicate is const. You can report the issue here:
http://connect.microsoft.com/feedback/default.aspx?SiteID=210
Of course, the workaround is easy, and it's good practice anyway to make
the predicate const. All that said, it shouldn't have compiled even in
debug mode, as your comparison class is a local type and doesn't have
linkage; you'll need to move it into namespace scope to use it as a
template argument. Also, don't use _T() when explicitly using wchar_t; use
_T() only with TCHAR. Use L"key2" instead of _T("key2") when dealing with
wchar_t.
--
Doug Harrison
Visual C++ MVP