为什么这样工作:从std :: string函数返回C字符串文本并调用c_str() [英] Why does this work: returning C string literal from std::string function and calling c_str()

查看:181
本文介绍了为什么这样工作:从std :: string函数返回C字符串文本并调用c_str()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们最近在大学里做了一场演讲,我们的教授告诉我们,在使用不同语言编程时,要注意不同的事情。
以下是C ++中的示例:

We recently had a lecture in college where our professor told us about different things to be careful about when programming in different languages. The following is an example in C++:

std::string myFunction()
{
    return "it's me!!";
}

int main(int argc, const char * argv[])
{
    const char* tempString = myFunction().c_str();

    char myNewString[100] = "Who is it?? - ";
    strcat(myNewString, tempString);
    printf("The string: %s", myNewString);

    return 0;
}

这将失败的想法是它是我!!使用char []隐式调用std :: string构造函数。这个字符串从函数返回,函数 c_str()返回一个指向 std :: string

The idea why this would fail is that return "it's me!!" implicitly calls the std::string constructor with a char[]. This string gets returned from the function and the function c_str() returns a pointer to the data from the std::string.

由于从函数返回的字符串在任何地方都不被引用,因此应立即解除分配。这是理论。

As the string returned from the function is not referenced anywhere, it should be deallocated immediately. That was the theory.

但是,让这个代码运行没有问题。
很好奇听到你的想法。
谢谢!

However, letting this code run works without problems. Would be curious to hear what you think. Thanks!

推荐答案

您的分析是正确的。您所拥有的是未定义的行为。这意味着几乎任何事情都可能发生。看来在你的情况下,用于字符串的内存,虽然解除分配,仍然保存原始内容,当你访问它。这通常发生,因为操作系统不清除解除分配的内存。它只是标记为可用于将来使用。这不是C ++语言必须处理的:它实际上是一个操作系统实现细节。就C ++而言,所有的未定义的行为都适用。

Your analysis is correct. What you have is undefined behaviour. This means pretty much anything can happen. It seems in your case the memory used for the string, although de-allocated, still holds the original contents when you access it. This often happens because the OS does not clear out de-allocated memory. It just marks it as available for future use. This is not something the C++ language has to deal with: it is really an OS implementation detail. As far as C++ is concerned, the catch-all "undefined behaviour" applies.

这篇关于为什么这样工作:从std :: string函数返回C字符串文本并调用c_str()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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