President Camacho
President Camacho

Reputation: 1910

Convert const wchar_t* into a WCHAR*

How do I make this to work? C++ types are really confusing:

std::wstring wquery = std::wstring(query.begin(), query.end());
//split names
std::vector<WCHAR*> split_names;
std::stringstream ss;
ss.str(names);
std::string name;
while (std::getline(ss, name, ',')) {
    split_names.push_back(
        (
            std::wstring(
                name.begin(),
                name.end()
            )
        ).c_str()
    ); //error can't assign const wchar_t* into WCHAR*
}

Upvotes: 1

Views: 6365

Answers (2)

President Camacho
President Camacho

Reputation: 1910

I solved it rewriting everything to:

//split names
std::vector<std::wstring> split_names;
std::stringstream ss;
ss.str(names);
std::string name;
while (std::getline(ss, name, ',')) {
    split_names.push_back(std::wstring(name.begin(), name.end()));
}
std::vector<const WCHAR*> pszTags;
pszTags.resize(split_names.size());
for (int i = 0; i < pszTags.size(); i++)
    pszTags[i] = split_names[i].c_str();

Sorry for the inconvenience.

Upvotes: 0

Nikita
Nikita

Reputation: 6427

C++ tries to keep you from mistakes. Here:

std::wstring(name.begin(), name.end())).c_str()

you create a temporary object std::wstring and get the pointer to the string content. Object will be destroyed right after you leave this block. As a result you will get an invalid pointer.

Don't store pointer to the temporary object into your std::vector<WCHAR*> split_names;.

Upvotes: 3

Related Questions