Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

unique_ptr compile error

Tags:

I guess this is embarrassing if I told you I cant get this to compile. would you please help me:

#include<memory>
using namespace std;

int  main()
{
    std::unique_ptr<int> p1(new int(5));
    return 0;
}
$ gcc main.cpp 
main.cpp: In function ‘int main()’:
main.cpp:6:2: error: ‘unique_ptr’ was not declared in this scope
main.cpp:6:13: error: expected primary-expression before ‘int’
main.cpp:6:13: error: expected ‘;’ before ‘int’

$ gcc --version
gcc (Ubuntu/Linaro 4.6.1-9ubuntu3) 4.6.1
like image 685
rahman Avatar asked Mar 19 '12 07:03

rahman


People also ask

What happens when Unique_ptr goes out of scope?

std::unique_ptr is a smart pointer that owns and manages another object through a pointer and disposes of that object when the unique_ptr goes out of scope. The object is disposed of, using the associated deleter when either of the following happens: the managing unique_ptr object is destroyed.

Does Unique_ptr call destructor?

Yes. Well the unique ptr has a function object that by default invokes delete on the pointed to object, which calls the destructor. You can change the type of that default deleter to do almost anything.

What does Unique_ptr get do?

std::unique_ptr::getReturns the stored pointer. The stored pointer points to the object managed by the unique_ptr, if any, or to nullptr if the unique_ptr is empty.

Can you move a Unique_ptr?

A unique_ptr can only be moved. This means that the ownership of the memory resource is transferred to another unique_ptr and the original unique_ptr no longer owns it. We recommend that you restrict an object to one owner, because multiple ownership adds complexity to the program logic.


2 Answers

This is just a guess.

Most likely you compiled your program like this (or similarly) :

g++ main.cpp

If you did, then the problem is that g++ uses c++03 as default. To use c++11 features (and std::unique_ptr), you need to use newer version of c++ :

g++ -std=c++11

or

g++ -std=c++14

and I would recommend to use also -Wall -Wextra -pedantic.

like image 134
BЈовић Avatar answered Sep 21 '22 11:09

BЈовић


If you are using Code::Blocks, go to Settings > Compiler > Global compiler settings > Compiler settings and look for the Have g++ follow the C++11 ISO C++ language standard [-std=c++11] and check it!

(Code::Blocks will add the -std=c++11 for you when compiling)

like image 44
Sevener Avatar answered Sep 21 '22 11:09

Sevener