开发者

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.


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

#include <new>

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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜