Samaursa
Samaursa

Reputation: 17241

Compiler crashes with const auto

I am using Visual Studio 2010 with SP1. The following code crashes the compiler:

template <typename T>
class MyClass
{
public:
  typedef int my_int;

  const my_int foo();

};

template <typename T>
const auto MyClass<T>::foo() -> my_int
// auto MyClass<T>::foo() -> const my_int // THIS WORKS!
{
  return my_int(1);
}

int main()
{
  MyClass<int> m;
  m.foo();
}

Note the commented line that fixes the issue. Am I using auto properly here (i.e. const qualifier on auto)? Is the workaround essentially the exact same thing (i.e. can I safely use it until the compiler's bug is fixed)? And lastly, am I the only one experiencing this issue, if not, I will file a bug report.

NOTE: I realize that const here makes little sense. I was trying to replicate the bug in a smaller project where in the actual project I am returning a const reference to an object.

Upvotes: 5

Views: 467

Answers (2)

Shafik Yaghmour
Shafik Yaghmour

Reputation: 158539

This is one of those cases where trying out code in multiple compilers may have helped you realize that using const auto with a trailing return type is an error. There are several online C++ compilers. If you had tried out this code in clang you would have received the following error(live example):

error: function with trailing return type must specify return type 'auto', not 'const auto'

The relevant section in the draft C++ standard is section 8.3.5 Functions paragraph 2 which says (emphasis mine):

In a declaration T D where D has the form

D1 ( parameter-declaration-clause ) cv-qualifier-seqopt
  ref-qualifieropt exception-specificationopt attribute-specifier-seqopt
    trailing-return-type

[...]T shall be the single type-specifier auto.[...]

Upvotes: 1

James McNellis
James McNellis

Reputation: 355187

The code is ill-formed in C++11: if there is a trailing return type, then the "normal" return type must be auto (the C++11 specification states at 8.3.5[dcl.fct]/2 that "T shall be the single type-specifier auto," where T is the "type" that appears before the name of the function).

All compiler crashes are compiler bugs, so it is a bug that the Visual C++ 2010 compiler crashes when compiling your program. This bug has been fixed, though; Visual C++ 2013 rejects the program with a proper compilation error.

Upvotes: 5

Related Questions