class ClassB {
int m_b;
public:
ClassB(int b) : m_b(b) {}
void PrintClassB() const {
cout << "m_b: " << m_b << endl;
}
};
int main(int argc, char* argv[])
{
const ClassB &af = ClassB(1);
af.PrintClassB(); // print m_b: 1 with vs2008 & gcc 4.4.3
}
Given the above code, I have difficulties to understand this snippet:
Q1> What does this line mean?
const ClassB &af = ClassB(1);
Here is my understanding:
af refers to a temporary variable ClassB(1) and after theexecution of this line, the temporary variable is destroyed and af
refers to an undefined variable. During this procedure, no
copy-constructor is called.
Then why we can still issue the following statement and obtain the results?
af.PrintClassB(); // print m_b: 1 with vs2008 & gcc 4.4.3
consthere extend the life time of the temporary object (i.e.,ClassB(1)) being created. It’s scope lasts untilaffalls out of scope;This is because,
afis nothing but the temporary object’s reference which was constructed passing1to it’s constructor.