gpt4 book ai didi

c++ - new运算符和构造函数参数的执行顺序

转载 作者:行者123 更新时间:2023-12-01 22:17:49 25 4
gpt4 key购买 nike

C++ 规范是否指定了 new C(A​​())operator new 的顺序和 A 的构造函数。
g++ 让它的顺序是 A() -> new -> C(),但 clang++ 让它是 new -> A() -> C().
差异是由未指定的行为引起的吗?

g++:7.4.0铿锵++:10.0.0

#include <iostream>
#include <cstdlib>

struct A {
A() {
std::cout << "call A()\n";
}
};

struct C {
C(A) {
std::cout << "call S()\n";
}

void *operator new(size_t s) {
std::cout << "call new()\n";
return malloc(s);
}
};

int main() {
void *p = new C(A());
}

最佳答案

Clang 是正确的。从 C++17 开始,执行顺序得到保证。 [expr.new]/19

The invocation of the allocation function is sequenced before the evaluations of expressions in the new-initializer.

operator new(分配函数)应该首先被调用,然后评估 new 初始化器中的表达式(即 A())。

在 C++17 之前,不保证顺序。 [expr.new]/18 (C++14)

The invocation of the allocation function is indeterminately sequenced with respect to the evaluations of expressions in the new-initializer.

<小时/>

gcc 似乎不符合 C++17(及更高版本);编译gcc10 in C++2a mode给出相同的结果。

关于c++ - new运算符和构造函数参数的执行顺序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59452554/

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