Login | Register   
RSS Feed
Download our iPhone app
Browse DevX
Sign up for e-mail newsletters from DevX

By submitting your information, you agree that devx.com may send you DevX offers via email, phone and text message, as well as email offers about other products and services that DevX believes may be of interest to you. DevX will process your information in accordance with the Quinstreet Privacy Policy.

Tip of the Day
Language: C++
Expertise: All
Mar 5, 1999



Building the Right Environment to Support AI, Machine Learning and Deep Learning

std::string Should Never be Initialized With a NULL Pointer

You can initialize std::string with a pointer to char. However, it does not check the pointer. When the pointer happens to be NULL the results are undefined:
using std::string;

const char * getDescription(int symbol); // returns NULL when symbol cannot not found

void writeToString  (string & str, int symbol){
  str = getDescription(symbol);  // sloppy: initializer might be NULL; undefined behavior in this case
To be on the safe side, you should explicitly check the pointer before you assign it:
void writeToString ( string & str, int symbol){
  const char *p = getDescription(symbol); 
  if (p) { 
    str = p; // now safe
Danny Kalev
Comment and Contribute






(Maximum characters: 1200). You have 1200 characters left.



Thanks for your registration, follow us on our social networks to keep up-to-date