C++ 中的字符串分配:为什么这样做? [英] string allocation in C++: why does this work?

查看:34
本文介绍了C++ 中的字符串分配:为什么这样做?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

void changeString(const char* &s){
    std::string str(s);
    str.replace(0, 5, "Howdy");
    s = str.c_str();
}

int main() {
    const char *s = "Hello, world!";
    changeString(s);
    std::cout << s << "\n";
    return 0;
}

当我运行这段代码时,它打印出你好,世界!"我认为 strchangeString 退出时会被破坏.我是否遗漏了 std::string 的分配方式?

When I run this code, it prints "Howdy, world!" I would think that str gets destroyed when changeString exits. Am I missing something with the way std::string gets allocated?

推荐答案

是的,str被销毁了;但字符串的内存没有被清除;您的s"指针指向空闲但未清除的内存.非常危险.

Yes, str is destroyed; but the memory of the string isn't cleared; your "s" pointer point to a free but non cleared memory. Very dangerous.

这篇关于C++ 中的字符串分配:为什么这样做?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆