shared_ptr: "is not a type" error

1.1k views Asked by At

I created a simple program to test smart pointers. I started with standard library but later I want to use boost. I have such compiling problem:

In file included from main.cpp:1:0:
test.hpp:14:21: error: ā€˜pā€™ is not a type
   shared_ptr<int>a (p);
                 ^

My files and makefile:

test.hpp:

#include <string>
#include <stdlib.h>
#include <vector>
#include <memory>
#include <boost/filesystem.hpp>

using namespace std;

class test{
    private:
        int* p = new int(10);
        shared_ptr<int>a (p);
    public:
        test() {}
        void get_pointer();
};

test.cpp:

#include "test.hpp"

void test::get_pointer()
{
    printf("%s\n",*a.get());
}

main.cpp:

#include "test.hpp"
#include <memory>
using namespace std;
int main()
{
    test tescik;
    tescik.get_pointer();
    int b;
    scanf("%d",&b);
    return 0;
}

makefile:

tester: main.cpp test.cpp
    g++ -o tester -std=c++11 main.cpp test.cpp -lboost_system -lboost_filesystem -lglfw3 -lGLU -lGL -lX11 -lXxf86vm -lXcursor -lrt -lm -lXinerama -lXrandr -lpthread -lXi -lopencv_core -lopencv_highgui -lopencv_imgproc -lopencv_video -lopencv_objdetect

I know I overextended compilation settings (opengl and boost), but I'll use them later. Any ideas why so simple program doesn't work?

2

There are 2 answers

2
fredoverflow On

You can't initialize data members like that in older versions of C++. Try this instead:

class test{
    private:
        int* p;
        shared_ptr<int> a;
    public:
        test() : p(new int(10)), a(p) {}
        void get_pointer();
};
0
KABoissonneault On

A brace-or-equal-initializer shall appear only in the declaration of a data member. (For static data members, see 9.4.2; for non-static data members, see 12.6.2). A brace-or-equal-initializer for a non-static data member shall not directly or indirectly cause the implicit definition of a defaulted default constructor for the enclosing class or the exception specification of that constructor.

You've used parentheses to initialize a data member directly in its declaration. Use a brace or an equal initializer, or move the initialization in the initializer list of the constructor.

Personally, I recommend to always use brace initialization (except maybe right now with auto because there's going to be a breaking change soon), because it's the only kind of initialization that can be used anywhere.