I have this simple test where I'm researching use of old style () vs list style {} in constructors. Unfortunately, it has a compilation warning and prints incorrect results for the old style X x()
construction case. Does anyone know why this particular case results in this warning?
My initial guess is X x();
is interpreted as calling a function. In that case X x;
or X x{};
should be used.
#include <iostream>
using namespace std;
struct X {
int x;
X() : x(0) {}
X(int xx) : x(xx) {}
friend ostream& operator<<(ostream& os, const X& a) {
return os << a.x;
}
};
int main(int argc, char *argv[])
{
X x();
cout << x << endl; // addr of X x() will never be NULL
X x2{};
cout << x2 << endl; // ok, prints 0 correctly
X x3(9);
cout << x3 << endl; // ok, prints 9 correctly
}
Compilation and invocation:
g++ -pedantic -Wall -fno-elide-constructors test150.cc && ./a.out
test150.cc: In function ‘int main(int, char**)’:
test150.cc:17:13: warning: the address of ‘X x()’ will never be NULL [-Waddress]
cout << x << endl; // addr of X x() will never be NULL
^
1
0
9
Aucun commentaire:
Enregistrer un commentaire