Cppcoreguidelines: Mention and enforce const unique_ptr pattern

Created on 12 Dec 2017  路  7Comments  路  Source: isocpp/CppCoreGuidelines

C++ Core Guidelines suggest to use either unique_ptr or shared_ptr for better code.
It should also mention const unique_ptr pattern for scoped based pointers

void f()
{
 // non-copyable, non-movable and non-resettable object
 auto const o = make_unique<Object>();
}

EDITED: Use make_unique

Most helpful comment

const unique_ptr<Object> o(new Object());

following R.11 : Avoid calling new and delete explicitly, how about

  const auto p = std::make_unique<Object>();

All 7 comments

Can't half your examples use const unique_ptr<Object>?

@jwakely Good point.
I will revisit examples and update the proposal with const unique_ptr.

const unique_ptr<Object> o(new Object());

following R.11 : Avoid calling new and delete explicitly, how about

  const auto p = std::make_unique<Object>();

@NN--- Thank you for this suggestion! Could you please prepare a PR with your changes?

@cubbimew Interesting point.
On the other hand there is class template argument deduction which reduce need of make_* functions.
http://en.cppreference.com/w/cpp/language/class_template_argument_deduction
Seems like there is something missing which will be both safe and with type deduction.

With make_* functions you can avoid using the new operator in product code.

Also, class-template argument deduction doesn't apply to c++14.

With make_* functions you can avoid using the new operator in product code.

That's true for make_unique and make_shared but they aren't relevant for class template argument deduction. I assume the previous comment was talking about object generators such as make_pair, make_tuple, make_optional etc. which exists to deduce the result type from the arguments. You wouldn't be using new in those cases anyway.

Was this page helpful?
0 / 5 - 0 ratings