在this Informit C++ guide ,我读到这个:
Using
malloc()
to create a non–POD object causes undefined behavior://disastrous! std::string *pstr =(std::string*)malloc(sizeof(std::string));
这里有两点没看懂:
- 指针是 POD。那这里为什么叫非POD呢? (也许我必须更好地理解 POD。)
- 这怎么会是灾难性的? (我想我必须为此了解字符串内部结构。)
请解释!
最佳答案
pointers are PODs then why here it is called non-POD
这里说的不是指针,而是std::string
。
这是灾难性的,因为 malloc
不调用构造函数,因此您将拥有 pstr
一个指向的 std::string
指针未正确构造的 std::string
。内存已分配但未正确初始化,因为缺少构造函数调用。
正确的做法是
std::string *pstr = new std::string;
干净的方法是在自动存储中只有一个变量:
std::string str;
关于c++ - 字符串指针的 malloc : how it can be disastrous?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11372939/