简体   繁体   English

C ++静态变量动态

[英]C++ static variables dynamic

在类上使用new运算符初始化静态动态变量是否可行或有意义?

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. 编辑:我误解了您的问题,但是我将其保留在这里,因为它确实建议了模糊的良好实践。

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

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 .) 或使用智能指针(请参阅Johannes答案 。)

In the statement: 在声明中:

static cMyClass* p = new cMyClass() ;

It would not be correct to call p a "static dynamic variable". p称为“静态动态变量”是不正确的。 It is a static pointer variable of type cMyClass* pointing to a dynamically allocated object. 它是cMyClass *类型的静态指针变量,指向动态分配的对象。

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. 有两个变量:1)静态的指针,和2)动态的对象。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM