gpt4 book ai didi

c++ - 如果普通默认构造函数不执行任何操作,为什么我们不能使用 malloc 创建普通可构造对象?

转载 作者:行者123 更新时间:2023-12-02 11:03:35 28 4
gpt4 key购买 nike

我很难理解以下引自 cppreference 的段落关于简单的默认构造函数。我已经搜索过 stackoverflow 但仍然没有得到明确的答案。所以请帮忙。

A trivial default constructor is a constructor that performs no action. All data types compatible with the C language (POD types) are trivially default-constructible. Unlike in C, however, objects with trivial default constructors cannot be created by simply reinterpreting suitably aligned storage, such as memory allocated with std::malloc: placement-new is required to formally introduce a new object and avoid potential undefined behavior.

具体来说,如果简单的默认构造函数什么都不做,为什么我们不能重新解释存储并假装存在给定类型的对象?您能否提供一些这可能导致的潜在未定义行为的示例?

最佳答案

P0593R5 “为低级对象操作隐式创建对象”给出了这个例子:

struct X { int a, b; };
X *make_x() {
X *p = (X*)malloc(sizeof(struct X));
p->a = 1;
p->b = 2;
return p;
}

并解释:

When compiled with a C++ compiler, this code has undefined behavior, because p->a attempts to write to an int subobject of an X object, and this program never created either an X object nor an int subobject.

Per [intro.object]p1 (C++17 Draft N4659),

An object is created by a definition, by a new-expression, when implicitly changing the active member of a union, or when a temporary object is created.

...这个程序没有做这些事情。

实际上,这是有效的,并且 UB 情况更多地被认为是标准中的缺陷而不是其他任何东西。本文的总体目标是提出一种解决该问题和类似情况而不破坏其他事情的方法。

关于c++ - 如果普通默认构造函数不执行任何操作,为什么我们不能使用 malloc 创建普通可构造对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59054209/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com