A better way to initialize a unique pointer is through an std::make_unique<some_type>(some_value) function, where we specify the type for the object in angle brackets and the value for the object pointer points at in parentheses:
#include <iostream> #include <memory> int main() /*from ww w. j a va2s . com*/ { std::unique_ptr<int> p = std::make_unique<int>(123); std::cout << *p; }
The std::make_unique function was introduced in the C++14 standard.
Make sure to compile with the -std=c++14 flag to be able to use this function.
We can create a unique pointer that points to an object of a class and then use its -> operator to access object members:
#include <iostream> #include <memory> class MyClass // w w w . j av a2s .c o m { public: void printmessage() { std::cout << "Hello from a class."; } }; int main() { std::unique_ptr<MyClass> p = std::make_unique<MyClass>(); p->printmessage(); }
The object gets destroyed once p goes out of scope.
So, prefer a unique pointer to raw pointer and their new-delete mechanism.
Once p goes out of scope, the pointed-to object of a class gets destroyed.
We prefer this function to raw new operator when creating unique pointers:
#include <iostream> #include <memory> class MyClass /*from w w w . j av a 2 s . co m*/ { private: int x; double d; public: MyClass(int xx, double dd) : x{ xx }, d{ dd } {} void printdata() { std::cout << "x: " << x << ", d: " << d; } }; int main() { auto p = std::make_unique<MyClass>(123, 456.789); p->printdata(); }