13
votes
class Foo {
 public:
  static const char *constant_string;
};

auto Foo::constant_string = "foo";

int main(void) {
};

Compiled with: gcc (Ubuntu/Linaro 4.6.3-1ubuntu5) 4.6.3 like this:

gcc -std=c++0x ./foo.cc 
./foo.cc:6:11: error: conflicting declaration ‘auto Foo::constant_string’
./foo.cc:3:22: error: ‘Foo::constant_string’ has a previous declaration asconst char* Foo::constant_string’
./foo.cc:6:11: error: declaration of ‘const char* Foo::constant_string’ outside of class is not definition [-fpermissive]

Is this intended behavior of the auto keyword, or a bug in gcc+

2
"foo" isn't really const char* but const char[4].Bo Persson
Not sure what you are trying to achieve here with auto. constant_string already is declared and static initialization should be ok without auto.kchoi

2 Answers

11
votes

It's disallowed by the language:

[C++11: 7.1.6.4]:

1 The auto type-specifier signifies that the type of a variable being declared shall be deduced from its initializer or that a function declarator shall include a trailing-return-type.

2 The auto type-specifier may appear with a function declarator with a trailing-return-type (8.3.5) in any context where such a declarator is valid.

3 Otherwise, the type of the variable is deduced from its initializer. The name of the variable being declared shall not appear in the initializer expression. This use of auto is allowed when declaring variables in a block (6.3), in namespace scope (3.3.6), and in a for-init-statement (6.5.3). auto shall appear as one of the decl-specifiers in the decl-specifier-seq and the decl-specifier-seq shall be followed by one or more init-declarators, each of which shall have a non-empty initializer.

4The auto type-specifier can also be used in declaring a variable in the condition of a selection statement (6.4) or an iteration statement (6.5), in the type-specifier-seq in the new-type-id or type-id of a new-expression (5.3.4), in a for-range-declaration, and in declaring a static data member with a brace-or-equal-initializer that appears within the member-specification of a class definition (9.4.2).

5A program that uses auto in a context not explicitly allowed in this section is ill-formed.

It's hard to prove a negative, but there's simply no explicit rule in the standard to allow auto in your case.

However, the same rules mean that the following is valid:

struct Foo {
   static constexpr auto constant_string = "foo";
};

int main() {}

(Note that the type of Foo::constant_string is char const* const rather than, say, char const[3]; this is an effect of using auto.)

4
votes

Visual C++ accepts

decltype(Foo::constant_string) Foo::constant_string = "foo";