what is difference between std::unique_ptr V/s std::make_unique ?
-
@Qt-embedded-developer the answer is basically: don't use 1 for the reasons given in my answer.
That said, you should really learn the use cases that comes with it. Using unique pointers is not a silver bullet. Especially in the case of Qt where there's the parent-child relationship paradigm.
-
@Qt-embedded-developer said in what is difference between std::unique_ptr V/s std::make_unique ?:
std::make_unique
I guess there is no difference between line1 and line2.
std::make_shared was introduced in C++11, but std::make_unique was not.
If you use C++ 11, you can use only line 1, but not Line2.
Line2 was introduced in C++ 14. Therefore, from C++14, Line1 and Line2 are same.
Line2 is preferred since it is consistent with make_shared.As @SGaist pointed out, auto classNamePtr = std::make_unique<ClassName>(&app); can be fatal.
-
@JoeCFD said in what is difference between std::unique_ptr V/s std::make_unique ?:
Line2 was introduced in C++ 14. Therefore, from C++14, Line1 and Line2 are same.
In this example yes, but not in general. Consider this:
class A; int g() { throw 0; } void f(std::unique_ptr<A> a, int p);
which can be used safely like this:
f(std::make_unique<A>(...), g());
while this may leak depending on how the compiler evaluates the arguments (which is unspecified):
f(std::unique_ptr<A>(new A()), g());
-
@JoeCFD said in what is difference between std::unique_ptr V/s std::make_unique ?:
If I have to, I prefer to define it as a shared pointer since it does not cost anything and why I look for trouble.
That's up to you, but keeping everything in
std::shared_ptr
, just because it's easy (for some definition of easy), is a rather lazy way of programming. There is a significant semantic difference between the two. -
you pass unique_ptr to a function when you want to transfer the ownership of the object contained inside the unique_ptr to the callee.
Using a shared_ptr is rarely the right choice.
If you don't transfer the ownership use a raw ptr or reference.
-
@JoeCFD said in what is difference between std::unique_ptr V/s std::make_unique ?:
As @SGaist pointed out, auto classNamePtr = std::make_unique<ClassName>(&app); can be fatal.
Can you elaborate this thing because why it can be fatal ?
-
-
@Qt-embedded-developer app looks like using stack(not heap) memory. when classNamePtr is cleared, it will try to destroy &app and your app will crash likely.
-