Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Comment: General cleanup and clarifications

...

Code Block
bgColor#FFcccc
langcpp
#include <new>
 
struct SomeType {
  SomeType() noexcept; // Performs nontrivial initialization.
  ~SomeType(); // Performs nontrivial finalization.
  void process_item() noexcept(false);
};
 
void f() {
  SomeType *pst = new (std::nothrow) SomeType();
  if (!pst) {
    // Handle error
    return;
  }
 
  try {
    pst->process_item();
  } catch (...) {
    // Handle error
    throw;
  }
  delete pst;
}

...

Code Block
bgColor#ccccff
langcpp
#include <new>

struct SomeType {
  SomeType() noexcept; // Performs nontrivial initialization.
  ~SomeType(); // Performs nontrivial finalization.

  void process_item() noexcept(false);
};

void f() {
  SomeType *pst = new (std::nothrow) SomeType();
  if (!pst) {
    // Handle error
    return;
  }
  try {
    pst->process_item();
  } catch (...) {
    // Handle error
    delete pst;
    throw;
  }
  delete pst;
}

...

Code Block
bgColor#ccccff
langcpp
struct SomeType {
  SomeType() noexcept; // Performs nontrivial initialization.
  ~SomeType(); // Performs nontrivial finalization.

  void process_item() noexcept(false);
};

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

...

Code Block
bgColor#ccccff
langcpp
struct A {/* ... */};
struct B {/* ... */};

 
class C {
  A *a;
  B *b;
protected:
  void init() noexcept(false);
public:
  C() : a(nullptr), b(nullptr) {
    try {
      a = new A();
      b = new B();
      init();
    } catch (...) {
      delete a;
      delete b;
      throw;
    }
  }
};

...

This compliant solution uses std::unique_ptr to create objects that clean up after themselves should anything go wrong in the C::C() constructor (see MSC17-CPP. Do not use deprecated or obsolescent functionality for more information on std::unique_ptr). The std::unique_ptr applies the principles of RAII to pointers.

...

hiddentrue

...

.

Code Block
bgColor#ccccff
langcpp
#include <memory>
 
struct A {/* ... */};
struct B {/* ... */};

class C {
  std::unique_ptr<A> a;
  std::unique_ptr<B> b;
protected:
  void init() noexcept(false);
public:
  C() : a(new A()), b(new B()) {
    init();
  }
};

...

Search for vulnerabilities resulting from the violation of this rule on the CERT website.

Related Guidelines

...