What is wrong with my mental model?

时间:2016-02-12 20:05:05

标签: c++

Why does this work...

string str("special_string");
string arr[10];
arr[0] = str;

while this causes a seg-fault?

string str("special_string");
string *buf = (string*)malloc(sizeof(string) * 10);
buf[0] = str; /* or *buf = str; */

Aren't both instances a by-value copy?

1 个答案:

答案 0 :(得分:0)

while this causes a seg-fault?

because you have a problem here:

string *buf = (string*)malloc(sizeof(string));

you only allocate memory but do not initialize object of type std::string properly as malloc() does not call ctor. If you use operator new instead you code would work:

string str("special_string");
string *buf = new string;
*buf = str;

and of course you should use delete instead of free() when you will need to destroy that object.