HeyJude HeyJude - 3 months ago 10
C++ Question

Generated constructor on POD vs non-POD cases

I know that if no constructor is declared for a class, the compiler will generate one.
However, after compiling the following (g++ or clang++) and doing

nm -C
with this code - that have a non-POD data member - I do see the generated Ctor:

class X
{
public:
void SetName(std::string name) {m_name = name;}
private:
std::string m_name;
};

int main()
{
X x1;
x1.SetName("jude");

return 0;
}


But with this code - with a POD data member - I don't:

class X
{
public:
void SetNum(int num) {m_x = num;}
private:
int m_x;
};

int main()
{
X x1;
x1.SetNum(8);

return 0;
}


I thought that I would see a generated constructor in both cases. Does this behavior complies with the standard? Or is it something else that's going on here?

Answer

In the case of

class X
{
public:
    void SetName(std::string name) {m_name = name;}
private:
    std::string m_name;
};

A constructor must be generated as m_name needs to be default constructed.

In the case of

class X
{
public:
    void SetNum(int num) {m_x = num;}
private:
    int m_x;
};

default constructing m_x is the same as doing nothing as the variable is left uninitialized. Since not generating and calling the constructor does the same thing the constructor would do the compiler can optimize it away under the "as-if" rule.

Comments