New

placement new usage

new an object on an exist memory.

class Foo
{
public:
    int val() { return _val; }
    Foo() : _val(0) { std::cout << "hello!\n"; }
private:
    int _val;
};

int main()
{
    const int chunk = 5;
    int i=0;
    char *buf = new char [sizeof(Foo)*chunk];

    for(char *p = buf;i<5;i++,p+=sizeof(Foo))
       Foo *tp = new (p) Foo;    // placement new usage!!
    return 0;
}
c++
Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-ShareAlike 3.0 License