-
Notifications
You must be signed in to change notification settings - Fork 396
Coding Standards Part 2 Performance and Safety
- [Part 0: Automated Analysis](Coding Standards Part 0 Automated Analysis)
- [Part 1: Style](Coding Standards Part 1 Style)
- [Part 2: Performance and Safety](Coding Standards Part 2 Performance and Safety)
- [Part 3: References and Further Reading](Coding Standards Part 3 References and Further Reading)
Variables should be declared as late as possible, and ideally, only when it's possible to initialize the object. Reduced variable scope results in less memory being used, more efficient code in general, and helps the compiler optimize the code further.
// Good idea
for (int i = 0; i < 15; ++i)
{
MyObject obj(i);
// do something with obj
}
// Bad Idea
MyObject obj; // meaningless object initialization
for (int i = 0; i < 15; ++i)
{
obj = MyObject(i); // unnecessary assignment operation
// do something with obj
}
// obj is still taking up memory for no reason
Exceptions cannot be ignored. Return values, such as using boost::optional
, can be ignored and if not checked can cause crashes or memory errors. An exception, on the other hand, can be caught and handled. Potentially all the way up the highest level of the application with a log and automatic restart of the application.
Stroustrup, the original designer of C++, makes this point much better than I ever could.
Raw memory access, allocation and deallocation, are difficult to get correct in C++ without risking memory errors and leaks. C++11 provides tools to avoid these problems.
// Bad Idea
MyClass *myobj = new MyClass;
// ...
delete myobj;
// Good Idea
std::shared_ptr<MyClass> myobj = make_shared<MyClass>();
// ...
// myobj is automatically freed for you whenever it is no longer used.
const
tells the compiler that a variable or method is immutable. This helps the compiler optimize the code and helps the developer know if a function side effects. Also, using const &
prevents the compiler from copying data unnecessarily. Here are some comments on const from John Carmack.
// Bad Idea
class MyClass
{
public:
MyClass(std::string t_value)
: m_value(t_value)
{
}
std::string get_value()
{
return m_value;
}
private:
std::string m_value;
}
// Good Idea
class MyClass
{
public:
MyClass(const std::string &t_value)
: m_value(t_value)
{
}
std::string get_value() const
{
return m_value;
}
private:
std::string m_value;
}