Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

This compliant solution complies with MEM31 MEM51-CPP. Properly deallocate dynamically allocated resources, however, while handling resource cleanup in catch clauses does work, it can have several disadvantages:

...

A better approach would be to employ RAII. This forces every object to 'clean up after itself' in the face of abnormal behavior, preventing the programmer from having to do so. This approach additionally benefits by not requiring statements to handle resource allocation errors in conformance with MEM32MEM52-CPP. Detect and handle memory allocation errors.

Code Block
bgColor#ccccff
langcpp
struct SomeType {
  void processItem() noexcept(false);
};

void f() {
  SomeType st;
  try {
    st.processItem();
  } catch (...) {
    // Handle error
    throw;
  }
}

...

This compliant solution utilizies std::unique_ptr to create objects that clean up after themselves should anything go wrong in the C::C() constructor. See VOID MEM00-CPP. Don't use auto_ptr where copy semantics might be expected for more information on std::unique_ptr.

...

Rule

Severity

Likelihood

Remediation Cost

Priority

Level

MEM44ERR40-CPP

Low

Probable

High

P2

L3

Automated Detection

...

Related Guidelines

Bibliography

[ISO/IEC 14882-2014]15.2, "Constructors and Destructors"
[Meyers 96]Item 9: "Use destructors to prevent resource leaks".
[Stroustrup 2001]"Exception-Safe Implementation Techniques"
[Cline 2009]

17.2, "I'm still not convinced: a 4-line code snippet shows that return-codes aren't any worse than exceptions;
why should I therefore use exceptions on an application that is orders of magnitude larger?"

...