c++ - 带有 GNU STL 的 GCC 4.8 为 std::string 构造函数生成错误代码?

标签 c++ gcc stl undefined-behavior

所以一点 C++ 代码:

void func( const std::string& theString )
{
    std::string theString( theString );
    theString += " more string";
    std::cout << theString;
}

使用 GCC 4.8VS 2013 可以很好地编译。根据我的 C++ 知识,代码可以使用局部变量 theString 进入范围,然后从函数参数中隐藏 theString。在 theString 构造点,范围内唯一的 theString 是传递给 std::string 构造函数的函数参数。构造的 std::string 然后被命名为 theString ,它进入范围并且是稍后在代码中使用的 theString 。呸!

然而,GCC 似乎传递给 std::string 构造函数的 theString 是本地 theString (尚未构建)导致编译的程序崩溃。使用 VS 2013,代码编译并运行良好。

所以,

  1. 我的代码正确吗?还是我在做一些超出规范的事情,这意味着 GCC 行为未定义。
  2. 这是 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/

相关文章:

c++ - 关于形式 (1)/( b ^ c ) 中的函数的数学问题

c++ - 迭代表示为 std::basic_string_view 的正则表达式子匹配

c++ - 多个 std::atomic<T> 条件

gcc 中的 C++11 thread_local - 备选方案

c++ - 在 Windows 上使用 g++ 编译 C++ 后出现 __gxx_personality_v0 错误

c++ - STL 容器类 : array

c++ - 如何检测在容器上迭代的第一个或最后一个元素?

c++ - 检测模块 (DLL) 何时卸载

c++ - 需要更改 clang 的包含路径

c++ - 使用 boost::bind 和 boost::static_pointer_cast 转换 boost::shared_ptr 的 vector