smoth190
smoth190

Reputation: 438

std::wstring not working with the [] operator of std::map<const wchar_t*, const char*>

I have a const std::map<const wchar_t*, const char*> which is in the global namespace. It looks like this:

.h file

typedef std::map<const wchar_t*, const char*> ShaderMap;

const ShaderMap::value_type rawShaderData[] = {
    ShaderMap::value_type( L"BasicShader_Vertex", 
        "..."
    ),
);

const int ElementCount = 2; //Length of rawShaderData
extern ShaderMap ShaderProgramsMap;

.cpp file

ShaderMap ShaderProgramsMap = ShaderMap( rawShaderData, rawShaderData + ElementCount );

I'm trying to access it elsewhere in my code like this:

std::wstring shaderKey = std::wstring( name + L"_Vertex" );
...
pShaderData = ShaderProgramsMap[shaderKey.c_str()];

Using the debugger, shaderKey is "BasicShader_vertex" but pShaderData is NULL. Is the problem with comparing the value of std::wstring::c_str to const wchar_t* or is it something elsewhere in the code?

Upvotes: 2

Views: 2557

Answers (2)

Steven
Steven

Reputation: 754

I don't actually see a std::map in your example code -- I see an array of std::map<>::value_type elements (i.e. const char*).

So, const ShaderMap::value_type ShaderProgramsMap[] = { ... };

is actually: std::pair<wchar_t const* const, char const*> const ShaderProgramsMap[] = { ... }

And, pShaderData = ShaderProgramsMap[shaderKey.c_str()];

is actually:

int nArrayIndex = int(shaderKey.c_str());
pShaderData = ShaderProgramsMap[nArrayIndex]; // actually an array, not a map

Upvotes: 1

David
David

Reputation: 28178

std::wstring shaderKey1 = std::wstring( name + L"_Vertex" );
ShaderProgramsMap[shaderKey1.c_str()] = "Whatever";

std::wstring shaderKey2 = std::wstring( name + L"_Vertex" );
pShaderData = ShaderProgramsMap[shaderKey2.c_str()];

The pointer returned by shaderKey1.c_str() is not the same as shaderKey2.c_str(). They are 2 different strings which both allocated their own data and are giving you a pointer to that allocation. They happen to store the same data, but you are only looking at the pointers. If you want to search and sort by string make the key a std::wstring, not a const wchar_t*. Along the same lines, the value should also very likely be std::string, not const char*, but I'll leave you to decide that.

Another problem with your original approach is that the pointer returned by shaderKey.c_str() will be dangling as soon as shaderKey goes out of scope.

Upvotes: 5

Related Questions