Pergunta

I am trying to assign a value to a wstring pointer and the value does not get assigned; however, when I break the creation and assignment of the pointer into two lines, it works. Why is this?

For example:

std::wstring* myString = &(L"my basic sentence" + some_wstring_var + L"\r\n");

The above does not work, but the below does work:

std::wstring temp = (L"my basic sentence" + some_wstring_var + L"\r\n");
std::wstring* myString = &temp;
Foi útil?

Solução

In the first example you are getting the address of a temporary. After that line has executed that wstring object you assigned myString to isn't available anymore (these are so called rvalues by the way). I think it should be obvious that in the second example you have a real object (a lvalue which is valid as long as it doesnt run ot of scope.

To overcome this limitation with the scope you can directly create a wstring on the heap, this might better suite your situation but without further information this is hard to tell:

std::wstring* myString = new std::wstring(L"my basic sentence" + some_wstring_var + L"\r\n");

The newly created wstring will me initialized with the contents of the temporary rvalue. Just do not forget to destroy the pointer after you are done with it.

With C++11 things have complicated so temporaries can be reused more often for performance reasons. But this topic is very though and will exceed this question. I just wanted to mention it because it might interesst you aswell. For a really great explanation take a look at this SO question: What are move semantics?

Outras dicas

std::wstring* myString = &(L"my basic sentence" + some_wstring_var + L"\r\n");

It points to a temporary object that its life time ends at the semicolon, so dereferencing the pointer and using it is undefined behavior.

std::wstring temp = (L"my basic sentence" + some_wstring_var + L"\r\n");
std::wstring* myString = &temp;

It points to a temporary object, but the life time is longer and dereferecing it is valid while that temporary object exists.

Of course you cannot assign the adress (that's what the & is) of a string constant to a variable. Have you thought about it? Where will the pointer point to?

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top