views:

91

answers:

4

Is it possible or makes sense to have static dynamic variables on a class, initialized with new operator?

+2  A: 

It may not make a lot of sense, but you can certainly do it:

 static int * p = new int(1);

The problem comes in having the object destroyed. This probably doesn't matter much in practice, unless the destructor has some side effect (such as writing to file) that you require, in which case a static smart pointer will (probably) do the job.

Having said that,

static int i = 1;

would seem preferable in almost all circumstances.

Edit: I misunderstood your question, but I'll leave this here, as it does recommend vaguely good practice.

anon
+2  A: 

Do you mean the following? Yes, it's allowed.

class Class {
  static Base *b;
};

Base *Class::b = new Derived();

Use smart pointers if you need it to be destroyed when the program exits

class Class {
  static boost::scoped_ptr<Base> b;
};

boost::scoped_ptr<Base> Class::b(new Derived());
Johannes Schaub - litb
In that case, it is possible for the class destructor to delete the static variable?
dmessf
@Zibd, the class destructor has no business with this. The object is created without any constructor of `Class` run, and it's going to be destroyed (if you order that) without its destructor doing anything either. Con/destructors are only in effect for instances of that class.
Johannes Schaub - litb
@Zibd: It's *possible* but probably not what you want. If you have a million instances of your class using the static variable, and just one stops existing, then the rest are using something you've deleted. Perhaps you should give us a bigger picture of what you're going for.
GMan
+1  A: 

And if you want to make sure it gets cleaned up after program exit:

struct foo
{
    static double* d;
};

namespace
{
    void delete_double(void)
    {
        delete foo::d;
    }

    double* get_double(void)
    {
        double* result = new double();
        atexit(delete_double);

        return result;
    }
}

double* foo::d = get_double();

Or use a smart pointer (see Johannes answer.)

GMan
+1  A: 

In the statement:

static cMyClass* p = new cMyClass() ;

It would not be correct to call p a "static dynamic variable". It is a static pointer variable of type cMyClass* pointing to a dynamically allocated object.

By calling it a "static dynamic" variable you make it sound like a paradox, when in fact it is simply a poor description of something that may be perfectly reasonable. There are two variables: 1) the pointer which is static, and 2) the object which is dynamic.

Clifford