在this Informit C++ guide中,我读到了这个:
使用
malloc()
创建非POD对象会导致未定义的行为://disastrous! std::string *pstr =(std::string*)malloc(sizeof(std::string));
我在这里不明白2点:
请解释一下!
答案 0 :(得分:5)
指针是POD,那么为什么在这里称为非POD
它不是在谈论指针,而是std::string
。
这是令人沮丧的,因为malloc
没有调用构造函数,因此您将pstr
指向std::string
指针,该指针指向未正确构造的std::string
。内存已分配,但未正确初始化,因为缺少构造函数调用。
正确的方法是
std::string *pstr = new std::string;
干净的方法是在自动存储中只有一个变量:
std::string str;
答案 1 :(得分:1)
这里你是分配标准字符串,而不是分配指向标准字符串的指针。请注意,您正在将sizeof(std::string)
传递给malloc;这就是你要回来多少内存...注意对象的大小大于指针的大小。如果您只是分配指针,那么您希望传入的大小为sizeof(std::string*)
。
您收到的指针是如何跟踪分配结果,但该指针不在堆上。这里它只是存储在普通变量中。如果你分配了一个指针,那么跟踪它的变量需要是一个指向指针的指针。
无论如何,如果你愿意,你可以合法分配一个指向标准字符串的指针,如下所示:
std::string str;
std::string** ptr_to_pstr = (std::string**)malloc(sizeof(std::string*);
*ptr_to_pstr = &str;
为什么你想要的并不完全清楚。但是,为什么你在C ++中使用malloc也不清楚。 :)