Here is a code sample from a C++ quiz:
#include <iostream>
struct X {
X(const char *) { std::cout << 1; }
X(const X &) { std::cout << 2; }
X(X &&) { std::cout << 3; }
};
X f(X a) {
return a;
}
X g(const char * b) {
X c(b);
return c;
}
int main() {
f("hello");
g("hello");
}
What will be the output of the program?
I think this way:
f(X a)
is called, and the constructor implicitly convertsconst char*
to X, so the output is 1- As we don't have an object to store the return value in, the return value is discarded, no output
g(const char*)
is called, andX c(b)
X(const char*)
The output is 1- The return value is one more time discarded - no output
So the answer is 11. The answer which is given to the quiz is 131. The answer, which I get with g++ 4.4.4-13 is 121.
It is said that this code was compiled with this command:
g++ -std=c++11 -Wall -Wextra -O -pthread
Where does the middle number come from? And why can it be 3 or 2?
-std=c++11
? The only thing it knows is-std=c++0x
.