Can I call constructor explicitly, without using new
, if I already have a memory for object?
class Object1{
char *str;
public:
Object1(c
You can use the following template
template <typename T, typename... Args>
inline void InitClass(T &t, Args... args)
{
t.~T();
new (&t) T(args...);
}
usage:
struct A
{
A() {}
A(int i) : a(i) {}
int a;
} my_value;
InitClass(my_value);
InitClass(my_value, 5);
Yes, when you've got your own allocated buffer you use placement new. Brian Bondy has a good response here in a related question:
What uses are there for "placement new"?
I think you're looking for Placement New. The C++ FAQ Lite has a good summary of how you do this. There are a few important gotchas from this entry:
#include <new>
to use the placement new syntax.