In C++, I want to define an object as a member of a class like this:
Object myObject;
However doing this will try to call it\'s parameterle
Others have posted solutions using raw pointers, but a smart pointer would be a better idea:
class MyClass {
std::unique_ptr
This avoids the need to add a destructor, and implicitly forbids copying (unless you write your own operator= and MyClass(const MyClass &).
If you want to avoid a separate heap allocation, this can be done with boost's aligned_storage and placement new. Untested:
template
class DelayedAlloc : boost::noncopyable {
boost::aligned_storage storage;
bool valid;
public:
T &get() { assert(valid); return *(T *)storage.address(); }
const T &get() const { assert(valid); return *(const T *)storage.address(); }
DelayedAlloc() { valid = false; }
// Note: Variadic templates require C++0x support
template
void construct(Args&&... args)
{
assert(!valid);
new(storage.address()) T(std::forward(args)...);
valid = true;
}
void destruct() {
assert(valid);
valid = false;
get().~T();
}
~DelayedAlloc() { if (valid) destruct(); }
};
class MyClass {
DelayedAlloc
Or, if Object is copyable (or movable), you can use boost::optional:
class MyClass {
boost::optional