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.
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.
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)) {
}
};
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.
© 2022 - 2024 — McMap. All rights reserved.
OtherClass*p
member. I mean ifbuf
is a union with aOtherClass
member.p
will have the the same value as &buf, making it unneeded right? – Trypanosomiasis