c++ - malloc for string pointers: how it can be disastrous? -


in this informit c++ guide, read this:

using malloc() create non–pod object causes undefined behavior:

//disastrous! std::string *pstr =(std::string*)malloc(sizeof(std::string)); 

i didn't understand 2 points here :

  • pointers pods. why called non-pod here? (maybe have understand pod better.)
  • how can disastrous? (i guess have understand string internals this.)

please explain!

pointers pods why here called non-pod

it's not talking pointer, std::string.

it's disastruous because malloc doesn't call constructor, you'll have pstr std::string pointer points std::string wasn't constructed. memory allocated wasn't initialized properly, because of missing constructor call.

the correct way is

std::string *pstr = new std::string; 

the clean way have variable in automatic storage:

std::string str; 

Comments

Popular posts from this blog

javascript - backbone.js Collection.add() doesn't `construct` (`initialize`) an object -

c++ - Accessing inactive union member and undefined behavior? -

php - Get uncommon values from two or more arrays -