Placement new and non-default constructors

Chris Masterton picture Chris Masterton · Oct 12, 2010 · Viewed 7.8k times · Source

Can I call the C++ placement new on constructors with parameters? I am implementing a custom allocator and want to avoid having to move functionality from non-default constructors into an init function.

class CFoo
{
public:
    int foo;
    CFoo()
    {
        foo = 0;
    }

    CFoo(int myFoo)
    {
        foo = myFoo;
    }
};

CFoo* foo = new (pChunkOfMemory) CFoo(42);

I would expect an object of type CFoo to be constructed at pChunkOfMemory using the second constructor. When using operator new am I stuck with default constructors only?

Solved! I did not #include <new>. After this, calling placement ::new worked fine with non-default constructors.

Answer

GManNickG picture GManNickG · Oct 12, 2010

To use placement new, you need to include the header <new>:

#include <new>

Otherwise the placement forms of operator new aren't defined.