How can a compiler generated default constructor be more efficient than a self-written one that does nothing but initialize members? [duplicate]

你离开我真会死。 提交于 2020-01-03 11:32:07

问题


Triggered by this answer I was reading in the core guidelines:

C.45: Don’t define a default constructor that only initializes data members; use in-class member initializers instead

The reasoning given is

Reason

Using in-class member initializers lets the compiler generate the function for you. The compiler-generated function can be more efficient.

Note that this is specifically about a default constructor that does nothing but initialize the members and the guideline suggests that one should not write such a constructor.

The "bad" example is:

Example, bad

class X1 { // BAD: doesn't use member initializers
    string s;
    int i;
public:
    X1() :s{"default"}, i{1} { }
    // ...
};

What can the compiler generated constructor do more efficient than the user-provided one in that particular example (or in any other example)?

Naively I would expect the initializer list giving the same opportunities for optimization as in-class initializers.

来源:https://stackoverflow.com/questions/56272431/how-can-a-compiler-generated-default-constructor-be-more-efficient-than-a-self-w

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