Short answer: It doesn't work.
This reference says that the default constructor of std::unique_ptr
creates an empty unique pointer, meaning it has no associated object.
The reason why this code prints hello
is because this statement
std::cout << "hello";
doesn't need anything of Bar
. It could just as well be a static method. Maybe the compiler inlines the function and replaces s.use()
with the std::cout
-statement. But even if it does call the method, you won't notice any errors since it doesn't access the memory of Bar
at all.
Make a slight change to your class and you will see what I mean:
class Bar
{
public:
Bar() : data(10) {};
~Bar() {};
void print() {
std::cout << "hello, data is: " << data;
}
int data;
};
Now, print
accesses invalid memory, because you never called new
(or even better: make_unique
). It may even work and print something to the console, but the output of data
will be garbage. If you're lucky, the application will crash.
Another reason why it appears to work (thanks Stas):
std::unique_ptr
defines operator->
, which simply returns the contained pointer, but does not check if the pointer points to valid memory. So pteste->
won't throw an exception.