Nick Heiner
Nick Heiner

Reputation: 122580

C++: Get LPCWSTR from wstringstream?

If I have a wstringstream, and I want to get its .str() data as a LPCWSTR, how can I do that?

Upvotes: 1

Views: 2165

Answers (2)

sbi
sbi

Reputation: 224159

You can do wstringstream.str().c_str() as DeadMG writes. However, the result of that call is only valid until the end of lifetime of the expression, this is part of.

Specifically, this

const LPCWSTR p = wss.str().c_str();
f(p); // kaboom!

will not work, because wstringstream.str() returns a temporary object and .c_str() returns a pointer into that object, and at the end of the assignment that temporary object will be destructed.

What you can do instead is either

f(wss.str().c_str()); // fine if f() doesn't try to keep the pointer

or

const std::wstring& wstr = wss.str(); // extends lifetime of temporary 
const LPCWSTR p = wstr.c_str();
f(p); // fine, too

because temporary objects bound to a const reference will have their lifetime extended for the reference's lifetime.

Upvotes: 12

Puppy
Puppy

Reputation: 147018

wstringstream.str().c_str();

Upvotes: 0

Related Questions