What's wrong with this:
wchar_t * t = new wchar_t;
t = "Tony";
I thought I could use a wchar_t pointer as a string...
The wchar_t type is an implementation-defined wide character type. In the Microsoft compiler, it represents a 16-bit wide character used to store Unicode encoded as UTF-16LE, the native character type on Windows operating systems.
The default value for wchar_t is zero so there's no need to even give any values in the brackets.
A pointer just points to a single value. This is important.
All you've done is allocated room for a single wchar_t
, and point at it. Then you try to set the pointer to point at a string (remember, just at the first character), but the string type is incorrect.
What you have is a string of char
, it "should" be L"Tony"
. But all you're doing here is leaking your previous memory allocation because the pointer holds a new value.
Rather you want to allocate enough room to hold the entire string, then copy the string into that allocated memory. This is terrible practice, though; never do anything that makes you need to explicitly free memory.
Just use std::wstring
and move on. std::wstring t = L"Tony";
. It handles all the details, and you don't need to worry about cleaning anything up.
Since you are a C# developer I will point out a few things c++ does different.
This allocates a new wchar_t and assigns it to t
wchar_t* t = new wchar_t
This is an array of constant char
"Tony"
To get a constant wchar_t array prefix it with L
L"Tony"
This reasigns t to point to the constant L"Tony" instead of your old wchar_t and causes a memory leak since your wchar_t will never be released.
t = L"Tony"
This creates a string of wide chars (wchar_t) to hold a copy of L"Tony"
std::wstring t = L"Tony"
I think the last line is what you want. If you need access to the wchar_t pointer use t.c_str(). Note that c++ strings are mutable and are copied on each assignment.
The c way to do this would be
const wchar_t* t = L"Tony"
This does not create a copy and only assigns the pointer to point to the const wchar array
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With