mirror of
https://github.com/cpp-best-practices/cppbestpractices.git
synced 2025-12-17 11:14:35 +03:00
Merge pull request #69 from olivif/olivif/initlist
Clarifying performance in POD vs other in initializer lists.
This commit is contained in:
35
03-Style.md
35
03-Style.md
@@ -225,6 +225,8 @@ It also makes it possible to have two separate files next to each other on one s
|
|||||||
## Initialize Member Variables
|
## Initialize Member Variables
|
||||||
...with the member initializer list.
|
...with the member initializer list.
|
||||||
|
|
||||||
|
For POD types, the performance of an initializer list is the same as manual initialization, but for other types there is a clear performance gain, see below.
|
||||||
|
|
||||||
```cpp
|
```cpp
|
||||||
// Bad Idea
|
// Bad Idea
|
||||||
class MyClass
|
class MyClass
|
||||||
@@ -239,11 +241,23 @@ private:
|
|||||||
int m_value;
|
int m_value;
|
||||||
};
|
};
|
||||||
|
|
||||||
|
// Bad Idea
|
||||||
|
// This leads to an additional constructor call for m_myOtherClass
|
||||||
|
// before the assignment.
|
||||||
|
class MyClass
|
||||||
|
{
|
||||||
|
public:
|
||||||
|
MyClass(MyOtherClass t_myOtherClass)
|
||||||
|
{
|
||||||
|
m_myOtherClass = t_myOtherClass;
|
||||||
|
}
|
||||||
|
|
||||||
|
private:
|
||||||
|
MyOtherClass m_myOtherClass;
|
||||||
|
};
|
||||||
|
|
||||||
// Good Idea
|
// Good Idea
|
||||||
// C++'s member initializer list is unique to the language and leads to
|
// There is no performance gain here but the code is cleaner.
|
||||||
// cleaner code and potential performance gains that other languages cannot
|
|
||||||
// match.
|
|
||||||
class MyClass
|
class MyClass
|
||||||
{
|
{
|
||||||
public:
|
public:
|
||||||
@@ -255,6 +269,21 @@ public:
|
|||||||
private:
|
private:
|
||||||
int m_value;
|
int m_value;
|
||||||
};
|
};
|
||||||
|
|
||||||
|
// Good Idea
|
||||||
|
// The default constructor for m_myOtherClass is never called here, so
|
||||||
|
// there is a performance gain if MyOtherClass is not is_trivially_default_constructible.
|
||||||
|
class MyClass
|
||||||
|
{
|
||||||
|
public:
|
||||||
|
MyClass(MyOtherClass t_myOtherClass)
|
||||||
|
: m_myOtherClass(t_myOtherClass)
|
||||||
|
{
|
||||||
|
}
|
||||||
|
|
||||||
|
private:
|
||||||
|
MyOtherClass m_myOtherClass;
|
||||||
|
};
|
||||||
```
|
```
|
||||||
|
|
||||||
In C++11 you can assign default values to each member (using `=` or using `{}`).
|
In C++11 you can assign default values to each member (using `=` or using `{}`).
|
||||||
|
|||||||
Reference in New Issue
Block a user