Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Placement new and non-default constructors

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.

like image 724
Chris Masterton Avatar asked Oct 11 '10 22:10

Chris Masterton


Video Answer


1 Answers

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

#include <new>

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

like image 54
GManNickG Avatar answered Sep 19 '22 12:09

GManNickG