Tuesday, 20 August 2013

Allocate memory on stack without calling constructor

Allocate memory on stack without calling constructor

I'd like to keep MyClass in the stack memory (simpler, faster) in the
following code, but avoid calling the default constructor:
#include <iostream>
class MyClass {
public:
MyClass() {
std::cout << "MyClass()" << std::endl;
}
MyClass(int a) {
std::cout << "MyClass(" << a << ")" << std::endl;
}
MyClass(const std::string& a) {
std::cout << "MyClass(\"" << a << "\")" << std::endl;
}
void doStuff() {
std::cout << "doStuff()" << std::endl;
}
};
int main(int argc, char* argv[]) {
bool something;
if (argc > 1)
something = 1;
else
something = 0;
MyClass c;
if (something)
c = MyClass(1);
else
c = MyClass("string");
c.doStuff();
return 0;
}
As far as I know, the only way to avoid calling the default constructor
would be to use a pointer, but then I would have to allocate in the heap
and deal with memory management. Is there any other way?

No comments:

Post a Comment