In g++ 3.3 the code
struct A
{
A(int x) : x(x) {}
int x;
};
works as expected: no name confusion and initalization is done
correctly. Is it standard behaviour? Not so long time ago I used to
write:
struct A
{
A(int x_) : x(x_) {}
int x;
};
This is risky since forgetting an underscore leads to _run-time_
errors:
struct A
{
A(int x_) : x(x) {}
int x;
};
It happaned to me at least twice...
thanks,
radu
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]
|
|
0
|
|
|
|
Reply
|
radugrigore
|
11/27/2004 2:13:39 AM |
|
On 26 Nov 2004 21:13:39 -0500, Radu Grigore wrote:
>In g++ 3.3 the code
>
>struct A
>{
> A(int x) : x(x) {}
> int x;
>};
>
>works as expected: no name confusion and initalization is done
>correctly. Is it standard behaviour?
Yes it is. There's an example in12.6.2 para 7 that does exactly this.
Also 12.6.2 para 2 says "Names in a meminitializerid
are looked up in the scope of the constructor’s class and, if not found
in that scope, are looked up in the scope containing the constructor’s
definition." - so names in a mem initializer id never refer to
constructor function parameters. For the record - an oldish book
called "The best C/C++ Tips Ever" by Anthony Porter recommends doing
this and also points out that the order of items in the mem initializer
list doesn't determine the order that members are actually initialized.
<quote 12.6.2/7>
Names in the expressionlist of a meminitializer are evaluated in the
scope of the constructor for which the meminitializer is specified.
[Example:
class X {
int a;
int b;
nt i;
nt j;
public:
onst int& r;
(int i): r(a), b(i), i(i), j(this>i) {}
};
initializes X::r to refer to X::a, initializes X::b with the value of te
constructor parameter i, initializes X::i with the value of the
constructor parameter i, and initializes X::j with the value of X::i;
this takes place each time an object of class X is created. ] [Note:
because the meminitializer are evaluated in the scope of the
constructor, the this pointer can be used in the expressionlist of a
meminitializer to refer to the object being initialized. ]
<end quote>
Other relevant sections in the std are 3.3.2 which defines local scope
and 3.3.7 which says that local names hide member names.
Graeme
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]
|
|
0
|
|
|
|
Reply
|
Graeme
|
11/29/2004 10:55:35 AM
|
|