Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can calls to memory allocation and constructor be interleaved with other operations required to perform a "new" expression?

Suppose I have a following class:

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

some function returning an int

int SomeFunction()
{
    return 0;
}

and this code:

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

Now I expect the following sequence:

  • SomeFunction() is run, then
  • ::operator new() is run to allocate memory for the object, then
  • class Sample constructor is run over allocated memory

Is this order fixed or can it be changed by an implementation such that say first memory is allocated, then SomeFunction() is called, then constructor is run? In other words, can call to operator new() function and call to class constructor be interleaved with anything?

like image 930
sharptooth Avatar asked Oct 21 '25 14:10

sharptooth


1 Answers

The order is unspecified. [5.3.4]/21 reads:

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.

like image 97
decltype Avatar answered Oct 23 '25 05:10

decltype



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!