本文介绍了GCC 4.8与GNU STL生成坏的代码std :: string构造函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 所以有点C ++代码: void func(const std :: string& theString) { std :: string theString(theString); theString + =more string; std :: cout<<字符串; } 可编译成 GCC 4.8 和 VS 2013 。从我的C ++知识,代码是好的,一个局部变量 theString 被带入范围,然后隐藏 theString 从函数参数。在 theString 构造的时候,范围中只有 theString 是函数参数,它传递给 std :: string 构造函数。构造的 std :: string 然后命名为 theString ,其范围为 theString 稍后在代码中使用。 Phew! 但是, GCC 看起来像 theString 传递给 std :: string 构造函数的是局部 theString (尚未构造)编译程序崩溃。与VS 2013的代码编译和运行良好。 因此, 我的代码正确吗? 这是GCC中的错误吗? 根据C ++标准(3.3.2声明点) 1名称的声明点紧接在完整声明符(第8条)之后, [例如: int x = 12; {int x = x; } 这里,第二个x被初始化为自己的。 -end example] 和(3.3.3块范围,#2) 在函数定义的最外面的块中不应重新声明参数名,也不会在任何处理程序的最外面的块中与一个function-try-block相关联。 So a bit of C++ code:void func( const std::string& theString ){ std::string theString( theString ); theString += " more string"; std::cout << theString;}which compiles fine with GCC 4.8 and VS 2013. From my C++ knowledge, the code is okay with a local variable theString being brought into scope which then hides theString from the function argument. At the point of theString construction, the only theString in scope is the function argument which is passed to the std::string constructor. The constructed std::string is then named theString which comes into scope and is theString used later in the code. Phew!However, GCC seems to act like theString passed to the std::string constructor is the local theString (which hasn't been constructed yet) causing the compiled program to crash. With VS 2013 the code compiles and runs fine.So,Is my code correct? Or am I doing something outside spec which means the GCC behaviour is undefined.Is this a bug in GCC? 解决方案 No, your code is invalid.According to the C++ Standard (3.3.2 Point of declaration) 1 The point of declaration for a name is immediately after its complete declarator (Clause 8) and before its initializer (if any), except as noted below.[ Example:int x = 12;{ int x = x; } Here the second x is initialized with its own (indeterminate) value. —end example ]And (3.3.3 Block scope, #2) A parameter name shall not be redeclared in the outermost block of the function definition nor in the outermost block of any handler associated with a function-try-block. 这篇关于GCC 4.8与GNU STL生成坏的代码std :: string构造函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 09-27 10:39