user5600884 user5600884 - 5 months ago 20
C++ Question

Unique Pointers in Modern c++

I have searched throughout the web quite a bit and have found so many different examples of

unique_ptr
implementation in modern c++. I have started to update all of my code starting with
::iterators
into the
auto
and etc. However, with the smart pointers I don't think I understand exactly what I am suppose to be doing.

With a standard pointer I have:

object *temp = new object();


Then with the new smart pointer I have:

unquie_ptr<object> temp(new object());


Is this not the correct way of implementation? If so, it seems to be more typing / work to make smart pointers when I have a simple cleanup function built at the end of my program?

Answer Source

You can use more performant std::make_unique and std::make_shared.

However, make_unique is not available in C++11, but is in C++14 and above

So

std::unique_ptr<object> = std::make_unique<object>();

else

auto p = std::make_unique<object>();

and similar things go for shared_ptr

In C++11, you can use your expression for unique_ptr.

unquie_ptr<object> temp(new object());