Re: regarding Auto and decltype
ManicQin wrote:
Hello everybody.
In Scott Meyers lecture notes he states that one of the differences
between Auto and decltype is that the decltype does not evaluate the
expression.
I have a question regarding the evaluation of the expression, in the
next scenario what should I expect:
class B
{
public:
B()
{
}
virtual B* Clone()
{
cout << "B" << endl;
return new B();
}
};
class D : public B
{
public:
D(){}
virtual D* Clone()
{
cout << "D" << endl;
return new D();
}
};
int main()
{
B* tmp = new D();
auto test1 = tmp->Clone(); //returns D*!!!
decltype(tmp->Clone()) test2 = tmp->Clone();
return 0;
}
Please note That D::Clone overloads with a different return type.
In my understanding if the "auto" is evaluating so it means that the
type of test1 should be D*, but VS10 understands different :) what am
I missing?
thank you.
I assume that what Scott means is that when you do
decltype(tmp->Clone()) test2 = tmp->Clone();
the tmp->Clone() in the decltype doesn't actually get evaluated (it's
only used for type deduction purposes). In the case of auto, there's no
expression similarly "associated with" the auto that could potentially
be evaluated in any case (it's just a stand-alone keyword). Note that
the expression on the right-hand side of the assignment involving auto
is evaluated at runtime, but then so is the tmp->Clone(); on the
right-hand side of the assignment involving decltype above - nothing
special about that.
The key point is that the compiler assigns types at *compile-time*
(since C++ is a statically-typed language). At that point, it has no
concept of "tmp points to a D" - all it deduces is that tmp->Clone() is
a call to B::Clone() since tmp is a B*. It therefore assigns test1 the
type returned by B::Clone(), namely B*. In other words, it uses the
static type of *tmp (B) when doing all of this, not the dynamic type
(D). The same is true in the test2 case.
Cheers,
Stu
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]