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
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.
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.
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.
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.
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
.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With