其他分享
首页 > 其他分享> > c – 初始化数组,放置新的,读取变量,定义的行为?

c – 初始化数组,放置新的,读取变量,定义的行为?

作者:互联网

给定一个类的唯一成员是char [10],它没有继承,也没有虚拟成员,它有一个构造函数,它没有以任何方式提及数组(这样它得到默认初始化 – >没有初始化,就像这样:

class in_place_string {
    char data[10];

    static struct pre_initialized_type {} pre_initialized;
    in_place_string(pre_initialized_type) {}  //This is the constructor in question

    in_place_string() :data() {} //this is so you don't yell at me, not relevent
};

它是否定义了将此类放置到已有数据的缓冲区中的行为,然后从数组成员中读取?

int main() {
    char buffer[sizeof(in_place_string)] = "HI!";
    in_place_string* str = new(buffer) in_place_string(in_place_string::pre_initialized);
    cout << str->data; //undefined behavior?
}

我很确定它没有很好地定义,所以我问这是实现定义还是未定义的行为.

解决方法:

我认为有关条款是8.5 [dcl.init]第12段:

If no initializer is specified for an object, the object is default-initialized. When storage for an object with automatic or dynamic storage duration is obtained, the object has an indeterminate value, and if no initialization is performed for the object, that object retains an indeterminate value until that value is replaced (5.17). [ Note: Objects with static or thread storage duration are zero-initialized, see 3.6.2. —end note ] If an indeterminate value is produced by an evaluation, the behavior is undefined except in the
following cases:

  • If an indeterminate value of unsigned narrow character type (3.9.1) is produced by the evaluation of:
    • the second or third operand of a conditional expression (5.16),
    • the right operand of a comma expression (5.18),
    • the operand of a cast or conversion to an unsigned narrow character type (4.7, 5.2.3, 5.2.9, 5.4), or
    • a discarded-value expression (Clause 5), then the result of the operation is an indeterminate value.
  • If an indeterminate value of unsigned narrow character type is produced by the evaluation of the right operand of a simple assignment operator (5.17) whose first operand is an lvalue of unsigned narrow character type, an indeterminate value replaces the value of the object referred to by the left operand.
  • If an indeterminate value of unsigned narrow character type is produced by the evaluation of the initialization expression when initializing an object of unsigned narrow character type, that object is initialized to an indeterminate value.

我不认为任何例外情况适用.由于在构造对象之后初始化之前读取了值,因此我认为代码会导致未定义的行为.

标签:placement-new,c,language-lawyer,undefined-behavior
来源: https://codeday.me/bug/20190830/1766731.html