开发者

C++ static variables dynamic

Is it possible or makes sense to have static dynamic variables on a cla开发者_如何学Pythonss, initialized with new operator?


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


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.


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


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜