new with multiple arguments in cppreference example

Viewed 132

From cppreference's new page.

new T;      // calls operator new(sizeof(T))
           // (C++17) or operator new(sizeof(T), std::align_val_t(alignof(T))))
new T[5];   // calls operator new[](sizeof(T)*5 + overhead)
           // (C++17) or operator new(sizeof(T)*5+overhead, >std::align_val_t(alignof(T))))
new(2,f) T; // calls operator new(sizeof(T), 2, f)
           // (C++17) or operator new(sizeof(T), std::align_val_t(alignof(T)), 2, f)

What does new(2, f) T; do?

2 Answers

What does new(2, f) T; do?

That second argument in placement-new can be used to pass a parameter to your custom T::operator new implementation.

Here is a toy example that triggers it (in the output, you can see that the parameter f=42.0is passed to T::operator new):

#include <iostream>

struct T {
  T() {
    std::cout << "T::T called\n";
  }

  void* operator new(size_t s, int x, double f) {
    std::cout << "T::new called with s=" << s << ", x=" << x << ", f=" << f << '\n';
    return malloc(x * s);
  }

  char data[512];
};

int main() {
  std::cout << "new T[5]:\n";
  new T[5];

  double f = 42.0;
  std::cout << "\nnew(2, f) T:\n";
  new(2, f) T;
}

Output:

new T[5]:
T::T called
T::T called
T::T called
T::T called
T::T called

new(2, f) T:
T::new called with s=512, x=2, f=42
T::T called

Be careful using tricks like this from examples online, they often are terrible.

The new keyword in C++ is shorthand for the following in C.

typedef struct {
    int a;
} Foo;

Foo *makeFoo(int a) {
    Foo *foo = (Foo *)malloc(sizeof(Foo));
    foo->a = a;
}

The malloc function reserves memory for that object, signaling it will be used as a pointer. The new operator does the same, but defaults sizeof(Foo). The parameters you see are the result of sizeof and an align_val_t instance.

Related