Question 11
Back to Exercise
What is the output of the following C++ program?
#include <iostream>
struct Temp {
int v;
explicit Temp(int x) : v(x) { std::cout << "+" << v; }
~Temp() { std::cout << "-" << v; }
int value() const { return v; }
};
int main() {
int total = Temp(1).value() + Temp(2).value();
std::cout << " =" << total << '\n';
return 0;
}
- A +1+2-2-1 =3 Correct
- B +1-1+2-2 =3
- C +1+2 =3-2-1
- D +2+1-1-2 =3
Correct Answer: Option A
Temporaries live until the end of the full expression, then are destroyed in reverse order of creation. (The order in which the two operands are evaluated is unspecified in general; this compiler evaluates left to right.)
Discussion & Comments 0
Share your method, a shortcut, or ask about a step you didn't follow.
No comments yet. Be the first to share your solution!