C ++ core principles C.44: default constructor is simple and does not throw the best

C.44: Prefer default constructors to be simple and non-throwing

C.44: The default constructor is simple and does not throw the best

 

Reason (reason)

Being able to set a value to "the default" without operations that might fail simplifies error handling and reasoning about move operations.

SUMMARY default constructor may be set to a default state without causing operation failure may, simplifies error handling and for the estimation of the moving operation.

 

Example, problematic (sample questions)

template<typename T>
// elem points to space-elem element allocated using new
class Vector0 {
public:
    Vector0() :Vector0{0} {}
    Vector0(int n) :elem{new T[n]}, space{elem + n}, last{elem} {}
    // ...
private:
    own<T*> elem;
    T* space;
    T* last;
};

This is nice and general, but setting a Vector0 to empty after an error involves an allocation, which may fail. Also, having a default Vector represented as {new T[0], 0, 0} seems wasteful. For example, Vector0<int> v[100] costs 100 allocations.

This code is clean and ordinary, but if had generated an empty Vector0 object after an error related to memory allocation may fail. At the same time, so the default Vector showed {new T [0], 0, 0} some waste. E.g. Vector0 <int> v [100] 100 required memory allocation.

 

100 memory allocation problem seems. Translator understanding is that as long as the primary distribution space 100 integers just fine.

Further new T [0] strange.

 

Example (Example)

template<typename T>
// elem is nullptr or elem points to space-elem element allocated using new
class Vector1 {
public:
    // sets the representation to {nullptr, nullptr, nullptr}; doesn't throw
    Vector1() noexcept {}
    Vector1(int n) :elem{new T[n]}, space{elem + n}, last{elem} {}
    // ...
private:
    own<T*> elem = nullptr;
    T* space = nullptr;
    T* last = nullptr;
};

Using {nullptr, nullptr, nullptr} makes Vector1{} cheap, but a special case and implies run-time checks. Setting a Vector1 to empty after detecting an error is trivial.

Use {nullptr, nullptr, nullptr} so Vector1 {} cost less, but a special case (since no data is generated, the translator's note) required runtime checking. After detecting the error Vector1 to empty handle the little things.

Enforcement (Suggestions)

  • Flag throwing default constructors.

  • Tip throw constructor exception.

 

Description link

 

https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#c44-prefer-default-constructors-to-be-simple-and-non-throwing

 


 

I think this article helpful? Welcome thumbs up and share it with more people.

Read more updated articles, please pay attention to micro-channel public number of object-oriented thinking []

Published 408 original articles · won praise 653 · views 290 000 +

Guess you like

Origin blog.csdn.net/craftsman1970/article/details/104464162