【问题标题】:Why did the assigning of an unrelated string cause another string to be modified? [duplicate]为什么分配一个不相关的字符串会导致另一个字符串被修改? [复制]
【发布时间】:2016-11-16 15:12:09
【问题描述】:

下面的示例,我将 fn 作为指向常量 c 字符串的 const 指针。当我声明一个不相关的其他 const 指针并将其分配给不同的常量 c 字符串时,原始 fn 被修改。我一直在尝试找出原因,但看不出是什么原因造成的?

输出:

原始 fn:sampleStrWithExtension

修改后的 fn:randomStr2ModifiedFn

int main() {
        std::string baseString = "sampleStr";
        std::string randomBaseString = "randomStr2";
        const char* const fn = (baseString + "WithExtension").c_str();
        std::cout << "Original fn: " << fn << std::endl;
        const char* const variableNotFn = (randomBaseString + "ModifiedFn").c_str();
        std::cout << "Modified fn: " << fn << std::endl;
        return 0;
    }

【问题讨论】:

  • fn = (baseString + "WithExtension").c_str() 不是一个非常危险的任务。由表达式baseString + "WithExtension" 创建的string 对象在此赋值完成后立即销毁,使变量fn 指向未分配的内存,可以随时重用。
  • x.c_str() 的生命周期永远不会超过 x 的生命周期。

标签: c++


【解决方案1】:
const char* const fn = (baseString + "WithExtension").c_str();

这会导致未定义的行为。

baseString + "WithExtension"

这会创建一个临时的std::string 对象。 std::string 上的 + 运算符返回一个新的 std::string,并且在此表达式的上下文中,返回的 std::string 成为一个临时对象。 c_str() 返回一个指向这个临时对象的内部缓冲区的指针。

c_str() 返回的指针只有在其std::string 被修改或被销毁之前才有效。在上述表达式的最后,临时对象被销毁。

稍后使用此指针会导致未定义的行为。

【讨论】:

  • 严格来说这不是未定义的行为。它只是一个指向不再存在的字符串的指针。当您取消引用它时会发生未定义的行为
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-03-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多