...
| Code Block | ||||
|---|---|---|---|---|
| ||||
#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 | ||||
|---|---|---|---|---|
| ||||
#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 | ||||
|---|---|---|---|---|
| ||||
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 | ||||
|---|---|---|---|---|
| ||||
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.
...
| hidden | true |
|---|
...
.
| Code Block | ||||
|---|---|---|---|---|
| ||||
#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
| SEI CERT C++ Coding Standard | MEM51-CPP. Properly deallocate dynamically allocated resources |
...