Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the syntax of using placement new in constructor initialize list

Suppose I have a class

class MyClass
int buf[10];
public:
MyClass(int i) {
    new (&buf) OtherClass(i); // How to move this to constructor initialize list?
}

Simply copy that line to the place after : not working.

like image 903
W.H Avatar asked Oct 17 '22 12:10

W.H


1 Answers

I'm not sure how you would use the constructed object; I suppose MyClass has a data member pointer to the object, then initialize the pointer like:

class MyClass {
int buf[10];
OtherClass* p;
public:
    MyClass(int i) : p(new (&buf) OtherClass(i)) {  
    }
};
like image 144
songyuanyao Avatar answered Nov 15 '22 04:11

songyuanyao