Joe Van Dyk wrote:
class Foo
{
public:
Foo() : smart_ptr_()
{
// reads some data
int param = read_some_data();
// based off this data, we can create a Something object
smart_ptr_ = smart_pointer<Something>(new Something(param));
}
private:
smart_pointer<Somethingsmart_ptr_;
};
As you can (hopefully) see, I've got a need to dynamically create an
object whose constructor needs some parameters that I can only get at
runtime.
Is the above way the best way to do it? Seems a bit clunky.
You can move the constructor logic to another method, which you can
then call on the initialize list.
Example:
class Foo
{
public:
Foo() : smart_ptr_( MakeSomething() )
{
}
static Something* MakeSomething()
{
// reads some data
int param = read_some_data();
// based off this data, we can create a Something object
return new Something(param);
}
private:
smart_pointer<Somethingsmart_ptr_;
};
In above example, I makde the method static, so as to avoid accessing
the object's data members. Any method you call in the initialize list
should avoid accessing the data members, because the Foo object is not
yet formed.