Search code examples
c++new-operator

new with multiple arguments in cppreference example


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?


Solution

  • 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