c++ - 对内存分配和构造函数的调用是否可以与执行 "new"表达式所需的其他操作交错?

标签 c++ class constructor new-operator

假设我有一个类:

 class Sample {
 public:
     Sample( int ) {}
 };

一些函数返回一个int

int SomeFunction()
{
    return 0;
}

和这段代码:

Sample* sample = new Sample( SomeFunction() );

现在我期望以下顺序:

  • SomeFunction() 运行,然后
  • ::operator new() 运行为对象分配内存,然后
  • class Sample 构造函数在分配的内存上运行

这个顺序是固定的还是可以通过实现来改变,比如首先分配内存,然后调用 SomeFunction(),然后运行构造函数?换句话说,调用 operator new() 函数和调用类构造函数可以与任何东西交错吗?

最佳答案

顺序未指定。 [5.3.4]/21 读:

Whether [operator new] is called before evaluating the constructor arguments or after evaluating the constructor arguments but before entering the constructor is unspecified. It is also unspecified whether the arguments to a constructor are evaluated if [operator new] returns the null pointer or exits using an exception.

关于c++ - 对内存分配和构造函数的调用是否可以与执行 "new"表达式所需的其他操作交错?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5882331/

相关文章:

C++:计算给定范围内可能的浮点值的数量

class - 在Lua中,每个 "object"都必须有自己的方法副本吗?

javascript - 如何使用 ES6 类创建一个不从 Object.prototype 继承的类?

c++ - 指针和构造函数的问题

c++ - memset 在模板类构造函数中泄漏内存

c++ - 使用 flex/bison 的多行注释声明

C++,同时读取和写入二进制文件

C++ libevent 用法(内存泄漏和删除运算符)

java - 如何检查当前方法的参数是否具有注释并在 Java 中检索该参数值?

C++构造函数中父类(super class)的init成员