c++ - 如何初始化静态类的疙瘩成语的d(指针)?

标签 c++ initialization static-class

这是我的标题代码:

#ifndef CLANDTYPES_H
#define CLANDTYPES_H

class CLandTypes
{
public:
    CLandTypes();
    ~CLandTypes();
private:
    class Pimple;
    static Pimple * d;
};

#endif // CLANDTYPES_H

因为它应该是一个静态类,所以我尝试在我的 cpp 文件中编写代码:

#include "clandtypes.h"

CLandTypes::Pimple * CLandTypes::d = new CLandTypes::Pimple();
...

但是有一点不对!

------------ 编辑------------

这是我的扩展 C++ 代码:

#include "clandtypes.h"

#include "qvector.h"
#include "qpair.h"

CLandTypes::Pimple * CLandTypes::d = new CLandTypes::Pimple();

class CLandTypes::Pimple
{
public:
    Pimple();
    ~Pimple();

    QVector > LandTypes;
};

CLandTypes::Pimple::Pimple()
    : LandTypes(NULL)
{
    LandTypes.push_back(qMakePair((unsigned int) 0, (QString)"undefined"));
    LandTypes.push_back(qMakePair((unsigned int) 1, (QString)"rocky"));
}

CLandTypes::Pimple::~Pimple(){}

CLandTypes::CLandTypes()
{
    if (!d)
    {
       d = new Pimple();
       if (!d)
       {
           throw std::bad_alloc();
       }
    }
}

CLandTypes::~CLandTypes()
{
    if(d)
    {
        delete d;
        d = NULL;
    }
}

我的两个错误是:

不完整类型'struct CLandTypes::Pimple'的无效使用
“struct CLandTypes::Pimple”的前向声明

最佳答案

移动这一行:

CLandTypes::Pimple * CLandTypes::d = new CLandTypes::Pimple();

CLandTypes::Pimple 的类定义之后.

反对您尝试使用new创建一个它一无所知的类的实例。

如果这样做,请删除检查 d 是否为 nullptr 的代码(又名 !d )在您对 CLandTypes::CLandTypes 的定义中构造函数。此代码可能会导致内存泄漏。此外,在您调用 new 后再次检查然后扔::std::bad_alloc完全没有必要,因为 new被定义为抛出 ::std::bad_alloc分配失败。

如果构造函数在初始化 CLandTypes::d 的静态初始化程序之前运行,则可能发生内存泄漏。运行。这只有在 CLandTypes 的构造函数时才会发生在其他地方的静态初始值设定项中使用。将会发生的是构造函数将赋值给d。然后是 d 的静态初始化程序将在稍后运行并覆盖该值,从而导致内存泄漏。

关于c++ - 如何初始化静态类的疙瘩成语的d(指针)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5776961/

相关文章:

c++ - 在构造函数中注册 weak_ptr 观察者

c++ - boost 日志 : Why it is showing duplicate the message?

c++ - 囤积分配器不是 "working"?

c++ - 将值从 vector 存储为字符串作为逗号分隔值

c++ - 如何使用构造函数初始化另一个类中的对象?

c# - 在静态类中访问或获取 Autofac 容器

c++ - 初始化成员结构的正确方法

performance - 通过空矩阵乘法初始化数组的更快方法? (Matlab)

c# - 在 appdomain 中加载静态类

c# - 静态类 VS 私有(private)构造函数