c++ - 字符串指针的 malloc : how it can be disastrous?

标签 c++ string malloc

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/

相关文章:

c++ - 类定义和使用错误

c++ - 为什么 random() 在 cstdlib 中工作? (Ubuntu 10.10)

C# 联合字符串

c - 动态二维数组转静态数组

c++ - 有没有办法停止 QGraphicsScene?

c++ - 解析树中的一元和二元减法

javascript - javascript语句中加入空字符串有什么用

python - 将特定单词后的单词提取为列表

c - 在编写我自己的 malloc、free 和 realloc 时遇到问题

c - C 中 malloc() 触发断点