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

2

7

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.

Trypanosomiasis answered 10/5, 2017 at 1:42 Comment(0)
Q
4

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)) {  
    }
};
Quenby answered 10/5, 2017 at 1:45 Comment(2)
Is there any other way to do it without the OtherClass*p member. I mean if buf is a union with a OtherClass member. p will have the the same value as &buf, making it unneeded right?Trypanosomiasis
@J.Doe AFAIK it's not possible; member intializer list is used for initializing members..Quenby
C
0

Here's a refinement of @songyunayao's answer, replete with the removal of *p:

template <class T2, class ...TArgs>
inline static monostate construct_helper(void* placement, TArgs&&...args)
{
    new (placement) T2(std::forward<TArgs>(args)...);
    return {};
}

class MyClass {
    union {
        std::byte buf[40];
        std::monostate dummy;
    };
public:
    MyClass(int i) : dummy(
        construct_helper<OtherClass>(buf, i)) {}
};

It's not the prettiest, but not so bad all things considered.

Curassow answered 18/5, 2023 at 18:41 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.