[16.21] How can I force objects of my class to always be created via new rather than as locals or global/static objects?
Use the Named Constructor Idiom.
As usual with the Named Constructor Idiom, the constructors are all private
or protected, and there are one or more public static create() methods
(the so-called "named constructors"), one per constructor. In this case the
create() methods allocate the objects via new. Since the constructors
themselves are not public, there is no other way to create objects of the
class.
class Fred {
public:
// The create() methods are the "named constructors":
static Fred* create() { return new Fred(); }
static Fred* create(int i) { return new Fred(i); }
static Fred* create(Fred const& fred) { return new Fred(fred); }
...
private:
// The constructors themselves are private or protected:
Fred();
Fred(int i);
Fred(Fred const& fred);
...
};
Now the only way to create
Fred objects is via
Fred::create():
int main()
{
Fred* p = Fred::create(5);
...
delete p;
...
}
Make sure your constructors are in the
protected section if you expect
Fred to have derived classes.
Note also that you can make another class Wilma a friend of Fred if you want to allow a Wilma to have a member object
of class Fred, but of course this is a softening of the original goal, namely
to force Fred objects to be allocated via new.