所以一点 C++ 代码:
void func( const std::string& theString )
{
std::string theString( theString );
theString += " more string";
std::cout << theString;
}
使用 GCC 4.8
和 VS 2013
可以很好地编译。根据我的 C++ 知识,代码可以使用局部变量 theString
进入范围,然后从函数参数中隐藏 theString
。在 theString
构造点,范围内唯一的 theString
是传递给 std::string
构造函数的函数参数。构造的 std::string
然后被命名为 theString
,它进入范围并且是稍后在代码中使用的 theString
。呸!
然而,GCC
似乎传递给 std::string
构造函数的 theString
是本地 theString
(尚未构建)导致编译的程序崩溃。使用 VS 2013,代码编译并运行良好。
所以,
- 我的代码正确吗?还是我在做一些超出规范的事情,这意味着 GCC 行为未定义。
- 这是 GCC 中的错误吗?
最佳答案
不,您的代码无效。
根据 C++ 标准(3.3.2 声明点)
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 ]
和(3.3.3 block 作用域,#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.
关于c++ - 带有 GNU STL 的 GCC 4.8 为 std::string 构造函数生成错误代码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26758267/