为什么将 std::string 初始化为“”(通过 lambda)会崩溃?

问题描述 投票:0回答:1

为什么将 std::string 初始化为“”(通过 lambda)会崩溃?

这不会崩溃:

static std::string strTest2 = [](){std::string * s = &strTest2; (*s) = "a"; return s->c_str();}();

这个技巧(先初始化为非空,但预期的最终值为空)不会崩溃:

static std::string strTest3 = [](){std::string * s = &strTest3; (*s) = "b"; (*s) = ""; return s->c_str();}();

在 (*s) = "" 处崩溃!因为空字符串?这很特别吗?分配给“”时,std::string 未构造/初始化?

static std::string strTest1 = [](){std::string * s = &strTest1; (*s) = ""; return s->c_str();}();

c++ lambda static initialization c++20
1个回答
0
投票

所有这些都是未定义的行为。其中一些不会导致崩溃这一事实无关紧要。它们都是无意义的代码。其中一些恰好为您“工作”。这次。

所有这些都是 UB 的原因相同:您在对象初始化之前访问该对象。

strTest
无法在用于初始化它的表达式中合法访问。这正是您的 lambda 试图做的事情。

为什么特定的一个会在您的编译器和构建设置上崩溃,而其他的则不会,这并不重要。它们都不代表有效的 C++ 代码。

© www.soinside.com 2019 - 2024. All rights reserved.