Explicitly defaulted constructors and initialisation of member variables

梦想与她 提交于 2019-12-23 18:06:07

问题


I'm slightly confused about what happens when a ctor is explicitly defaulted.

Are the two code samples below equivalent?

Are there any constraints on Y to be able to use the first option?

class X
{
public:
    X() = default;

private:
    Y m_y;
};

class X
{
public:
    X() : m_y() {}

private:
    Y m_y;
};

回答1:


There are two possible sources of differences.

  1. X() = default; is not user-provided. X() : m_y() {} is. The former can be trivial; the latter is never trivial. Also, they will behave differently if an X object is value-initialized.

  2. The set of initializations performed by X() = default; is equivalent to that of X() {}, which default-initializes m_y. X() : m_y() {} value-initializes m_y. Depending on what Y is, this can be different. For example, if Y is int, then default-initialization will leave it with an indeterminate value, while value-initialization will set it to zero.




回答2:


There are the same. With explicit cto'rs you only enforce his creation. Otherwise, the compiler can avoid create it if you are not using the default constructor. May be interesting when creating shared libraries. For reference http://en.cppreference.com/w/cpp/language/default_constructor



来源:https://stackoverflow.com/questions/29646685/explicitly-defaulted-constructors-and-initialisation-of-member-variables

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!