假设我有一个类:
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/