Vladislav Martin
Vladislav Martin

Reputation: 1684

C++: unique_ptr not initializing correctly

myMain.cpp:

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

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

I am initializing in global scope because loading all the data into the properties of this class takes a while, so I'd like to do it once and have that data persist until I give an explicit command to delete it (classPtr.reset(nullptr)).

When I try to compile this: g++ myMain.cpp -o myMain.o I get: error: expected initializer before '<' token.

Why am I getting this error?

I've defined myClass in myClass.h and myClass.cpp; I think the error has to do with the constructor. I've simplified code & included only the important lines below.

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

EDIT: Following tip from @FrançoisAndrieux I have fixed my constructor.

myClass.cpp:

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

Upvotes: 0

Views: 564

Answers (2)

Fran&#231;ois Andrieux
Fran&#231;ois Andrieux

Reputation: 29032

There are two significant problems:

  1. since you are using gcc 4.8.5, remember to use the flag -std=c++11 otherwise std::unique_ptr will not be available.

  2. end your class definition with a ;. The semi-colon is required in C/C++ when declaring types. Because you did not use a ;, you did not declare myClass as a type, and so it follows that the line static std::unique_ptr<myClass> classPtr; will produce an error since myClass is not a valid type.

Upvotes: 2

Cory Kramer
Cory Kramer

Reputation: 118001

Your initialization of your data member should either be

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

Or more simply

data()

Upvotes: 0

Related Questions