编译器与const auto崩溃

时间:2013-04-29 00:27:26

标签: c++ visual-studio-2010 auto

我在SP1中使用Visual Studio 2010。以下代码使编译器崩溃:

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();
}

请注意修复此问题的注释行。我在这里正确使用auto(即const上的auto限定词吗?解决方法基本上是完全相同的(即我可以安全地使用它,直到编译器的错误被修复)?最后,我是唯一遇到此问题的人,如果没有,我会提交错误报告。

注意:我意识到这里的const毫无意义。我试图在一个较小的项目中复制bug,在实际项目中我返回一个const对象的引用。

2 个答案:

答案 0 :(得分:3)

代码在C ++ 11中格式不正确:如果存在尾随返回类型,则“正常”返回类型必须为auto(C ++ 11规范的状态为8.3.5 [ dcl.fct] / 2“T应该是单个类型说明符 auto,”其中T是出现在函数名称之前的“类型”) 。

所有编译器崩溃都是编译器错误,因此在编译程序时,Visual C ++ 2010编译器崩溃是一个错误。但是这个bug已经修复了; Visual C ++ 2013使用正确的编译错误拒绝该程序。

答案 1 :(得分:1)

这是在多个编译器中尝试代码可能帮助您意识到使用带有尾随返回类型的const auto的错误的情况之一。有几个online C++ compilers。如果您在clang中试用了此代码,则会收到以下错误( live example ):

  

错误:具有尾随返回类型的函数必须指定返回类型'auto',而不是'const auto'

C ++标准草案中的相关部分是8.3.5 功能 2 ,其中说明了(强调我的):< / p>

  

在声明T D中,D的格式为

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

[...] T应为单一类型说明符自动。[...]