C++:unique_ptr 未正确初始化

C++: unique_ptr not initializing correctly

myMain.cpp:

#include <memory>
#include "myClass.h"

static std::unique_ptr<myClass> classPtr; // Error thrown here
...

我正在全局范围内初始化,因为将所有数据加载到这个 class 的属性中需要一段时间,所以我想做一次并让数据持续存在,直到我给出明确的命令删除它 (classPtr.reset(nullptr))。

当我尝试编译时:g++ myMain.cpp -o myMain.o 我得到:error: expected initializer before '<' token.

为什么会出现此错误?

我在myClass.hmyClass.cpp中定义了myClass;我认为错误与构造函数有关。我已经简化了代码并仅包含下面的重要行。

myClass.h:

class myClass {
    std::string dataPath;
    std::vector<double> data;
public:
    myClass(std::string P = "./path/to/data-file.csv");
    ~myClass() {}
    const double findPercentile(double percentile = 0.0);
}

编辑:根据@FrançoisAndrieux 的提示,我修复了我的构造函数。

myClass.cpp:

myClass::myClass(const std::string P) : 
            dataPath(P) {
    // read data-sets into class member variables
}

您的 data 成员的初始化应该是

data(std::vector<double>())

或者更简单地说

data()

有两个重大问题:

  1. 因为你使用的是gcc 4.8.5,记得使用flag -std=c++11否则std::unique_ptr将无法使用

  2. ; 结束您的 class 定义。 C/C++ 声明类型时需要分号。因为您没有使用 ;,所以您没有将 myClass 声明为类型,因此行 static std::unique_ptr<myClass> classPtr; 将产生错误,因为 myClass 不是有效类型。