Reputation: 10490
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?
Upvotes: 1
Views: 79
Reputation: 179991
The output of nm -C
is not bound by the as-if rule. Remember, inline
is just a hint to the compiler, and it may use any other hint it sees fit as well - including the complexity of a function. Obviously these two constructors vary in complexity. In fact, in the POD case the generated ctor literally is trivial, and it is entirely reasonable for a compiler to inline that.
Upvotes: 0
Reputation: 180945
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.
Upvotes: 4