Reputation: 14112
Consider the 3 ways of constructing an object:
1)
LogTreeItem::LogTreeItem(const QList<QVariant>& data, LogTreeItem* parent) :
m_parentItem {parent}, m_itemData {data}
{
}
2)
LogTreeItem::LogTreeItem(const QList<QVariant>& data, LogTreeItem* parent) :
m_parentItem (parent), m_itemData (data)
{
}
3)
TreeItem::TreeItem(const QList<QVariant> &data, TreeItem *parent)
{
m_parentItem = parent;
m_itemData = data;
}
Are they 100% equal? if not, where they differ? what are any advantage/disadvantage associated with each method?
I am guessing some stuff about copy assignment, move constructor or some advanced things in modern c++11 and beyond is getting done in case of 1 and 2.
Upvotes: 1
Views: 109
Reputation: 283614
The first and second will do the same thing for most types. However, for types having a constructor that accepts a std::initializer_list
, the first will prefer that and the second will prefer an ordinary constructor. The classic example is std::vector
with two arguments -- are they two items to put into the vector, or one item with a repetition count.
The third version isn't controlling the construction at all. As Mateusz correctly notes, the default constructor is used for object creation, and then the value is provided via assignment. On many types, some parameters can only be set during construction and cannot be changed during assignment, and this method won't work at all. Also consider references, which must be bound at construction time, and const
members, which have to be constructed with their final value because assignment is disabled.
Upvotes: 6
Reputation: 141
In the third example, members are first created with default constructor and then copy-assigned.
Upvotes: 4