Deprecated conversion from string const. to wchar_t*

Zac picture Zac · Sep 23, 2010 · Viewed 8.9k times · Source

Hello I have a pump class that requires using a member variable that is a pointer to a wchar_t array containing the port address ie: "com9".

The problem is that when I initialise this variable in the constructor my compiler flags up a depreciated conversion warning.

pump::pump(){
   this->portNumber = L"com9";}

This works fine but the warning every time I compile is anoying and makes me feel like I'm doing something wrong.

I tried creating an array and then setting the member variable like this:

pump::pump(){
   wchar_t port[] = L"com9";
   this->portNumber = port;}

But for some reason this makes my portNumber point at 'F'.

Clearly another conceptual problem on my part.

Thanks for help with my noobish questions.

EDIT:

As request the definition of portNumber was:

    class pump
{
private:
   wchar_t* portNumber;
}

Thanks to answers it has now been changed to:

    class pump
{
private:
   const wchar_t* portNumber;
}

Answer

GManNickG picture GManNickG · Sep 23, 2010

If portNumber is a wchar_t*, it should be a const wchar_t*.

String literals are immutable, so the elements are const. There exists a deprecated conversion from string literal to non-const pointer, but that's dangerous. Make the change so you're keeping type safety and not using the unsafe conversion.

The second one fails because you point to the contents of a local variable. When the constructor finishes, the variable goes away and you're pointing at an invalid location. Using it results in undefined behavior.

Lastly, use an initialization list:

pump::pump() :
portNumber(L"com9")
{}

The initialization list is to initialize, the constructor is to finish construction. (Also, this-> is ugly to almost all C++ people; it's not nice and redundant.)