Search code examples
c++new-operator

Calling the new operator with two arguments but without assignment


I found this code and I don't understand, why it works in the project. The structure of the code is:

class MyClass {
    int value;
};

struct MyStruct {
    MyClass classA;
    MyClass classB;
};

int main() {

    MyStruct myStruct;

    new (&((&myStruct)->classA)) MyClass();
    new (&((&myStruct)->classB)) MyClass();
}

(The inner ampersand was added by me to create a smaller example. In the source myStruct is a pointer).

The compiler says

In function int main()
error: no matching function for call to ‘operator new(sizetype, MyClass*)’
    new (&((&myStruct)->classA)) MyClass();
                                         ^
note: candidates are:
note: void* operator new(long unsigned int)
note:   candidate expects 1 argument, 2 provided

Maybe I'm missing something important. It's a big project and I can't copy it. I'm not able to create a MWE. I hope someone can explain to me the main idea behind this code and what I have to change to compile it.


Solution

  • Placement new is one of those C++ language features that require an appropriate header to be included before one can even attempt to use them.

    When using placement new, the expression must call an overload of operator new as part of its evaluation. This overload, to be exact:

    void* operator new (std::size, void*);
    

    But this function is not automatically declared for you in every translation unit. So to pull it in, you must include the correct header (<new>).


    As a side note, that code you showed is very broken. It constructs the members of myStruct twice! Which for non-trivial cases could wreck havoc.

    The proper way to very explicitly initialize myStruct is like this:

    MyStruct myStruct {
      {}, // Default construct classA
      {}  // Default construct classB
    };