When initializing wchar_t* data-members.

Is it generally better to initialize string data members as nullptr or as a zero-size array?

I can understand the former is superior from a memory-use perspective and also not requiring the extra allocation step. However, many string management functions will throw an exception - wcslen for instance - if you pass them a null pointer. Therefore I am finding any performance gained is somewhat wiped out by the extra if(pstString==nullptr) guards I have to use where it is possible a wchar_* may still be at null when the function is called.
Last edited on
It really depends on you and how you plan on using the variable. In your case initializing it to a zero length string seems like a good idea.

If you write your own methods or use methods that make it more efficient to set it to NULL, then that is what you should do.
A very fair point!

After doing more research here and elsewhere I'm getting the feeling that while unnecessary allocations are not advisable they are equally not considered the huge performance red flags they used to be. Perhaps faster computers and cheap physical memory has removed some of the disfavour placed on allocation?
> Is it generally better to initialize string data members as nullptr or as a zero-size array?

It is generally better to use std::wstring and let the implementation handle default initialisation.
http://en.cppreference.com/w/cpp/string/basic_string
Lolzor!!! But you are talking about the standard library string class.

I don't like using an encapsulated string class - not one I haven't made myself! Which... oddly enough, is part of what I am working on when tripping over this nullptr/0-length-string dilemma...

The grandfather-paradox of programming!!!
Last edited on
Topic archived. No new replies allowed.