1 - Use Initialization Lists
Always use initialization lists in constructors. For example, use
TMyClass::TMyClass(const TData &data) : m_Data(data)
{
}
rather than
TMyClass::TMyClass(const TData &data)
{
m_Data = data;
}
Without initialization lists, the variable's default constructor is invoked behind-the-scenes prior to the class's constructor, then its assignment operator is invoked. With initialization lists, only the copy constructor is invoked.
2 - Initialize on Declaration
Whereever possible, initialize variables at the time they're declared. For example,
TMyClass myClass = data;
is faster than
TMyClass myClass;
myClass = data;
Declaration then initialization invokes the object's default constructor then its assignment operator. Initializing in the declaration invokes only its copy constructor.
3 - Delay Variable Declarations
Leave variable declarations right until the point when they're needed. Remember that when a variable is declared its constructor is called. This is wasteful if the variable is not used in the current scope.
No comments:
Post a Comment