Simplifies the syntax of placement new.
template <class T, class... Args>
T* pnew(T& obj, Args&&... args) {
return (T*)new ((void*)&obj) T(std::forward<Args&&>(args)...);
}
For example, it can be used as follows. You can also pass constructor arguments.
class my_class {
int _a;
public:
my_class(int a = -1) : _a(a) {}
};
my_class obj_1; // This constructor is not called!
my_class obj_2; // This constructor is not called!
void setup() {
mwx::pnew(obj_1); // Equivalent to my_class obj_1;
mwx::pnew(obj_2, 2); // Equivalent to my_class obj_2(2);
...
}
Background
Due to compiler constraints, constructors of global objects are not called. One method to initialize them is using placement new. However, the placement new syntax can appear verbose.
Another method is to use std::unique_ptr
(or eastl::unique_ptr
).
std::unique_ptr<my_class> obj_3;
void setup() {
obj_3.reset(new my_class(3));
// On TWELITE microcontrollers, `new` can only allocate once and `delete` cannot be used,
// so in practice it is equivalent to a global object.
}