dmessf
dmessf

Reputation: 1013

C++ static variables dynamic

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

Upvotes: 1

Views: 2673

Answers (4)

Clifford
Clifford

Reputation: 93476

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.

Upvotes: 1

Johannes Schaub - litb
Johannes Schaub - litb

Reputation: 506965

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());

Upvotes: 2

GManNickG
GManNickG

Reputation: 503845

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.)

Upvotes: 1

anon
anon

Reputation:

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.

Upvotes: 2

Related Questions