with the member initializer list
// bad
class MyClass
{
public:
MyClass(int t_value)
{
m_value = t_value;
}
private:
int m_value;
};
// good
class MyClass
{
public:
MyClass(int t_value)
: m_value(t_value)
{
}
private:
int m_value;
};
... when it is semantically correct. Pre-increment is faster then post-increment because it does not require a copy of the object to be made.
// Correct
for (int i = 0; i < 15; ++i)
{
std::cout << i << std::endl;
}
// incorrect
for (int i = 0; i < 15; i++)
{
std::cout << i << std::endl;
}
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.
// bad
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
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;
}
Very nice and detailed, thank you.