简体   繁体   English

函数返回的字符串文字的生命周期

[英]Lifetime of a string literal returned by a function

Consider this code: 考虑以下代码:

const char* someFun() {
    // ... some stuff
    return "Some text!!"
}

int main()
{
   { // Block: A
      const char* retStr = someFun();
      // use retStr
   }
}

In the function someFun() , where is "Some text!!" someFun()函数中, "Some text!!"在哪里? stored (I think it may be in some static area of ROM) and what is its 存储(我认为它可能在ROM的某些静态区域中),它的作用是什么 scope 范围 lifetime? 一生?

Will the memory pointed by retStr be occupied throughout the program or be released once the block A exits? retStr指向的内存是在整个程序中占用还是在块A退出后释放?

The C++ Standard does not say where string literals should be stored. C ++标准未说明应将字符串文字存储在何处。 It does however guarantee that their lifetime is the lifetime of the program. 但是,它的确保证了它们的生命周期是程序的生命周期。 Your code is therefore valid. 因此,您的代码是有效的。

The "Some text!!" "Some text!!" does not have a scope . 没有范围 Scope is a property of a named entity. 范围命名实体的属性。 More precisely, it is a property of the name itself. 更确切地说,它是名称本身的属性。 "Some text!!" is a nameless object - a string literal. 是一个无名的对象-字符串文字。 It has no name, and therefore any discussions about its "scope" make no sense whatsoever. 它没有名称,因此任何有关其“范围”的讨论都毫无意义。 It has no scope. 它没有范围。

What you seem to be asking about is not scope . 您似乎要问的不是范围 It is lifetime or storage duration of "Some text!!" "Some text!!" 寿命保存期限 . String literals in C/C++ have static storage duration , meaning that they live "forever", ie as long as the program runs. C / C ++中的字符串文字具有静态存储持续时间 ,这意味着它们可以“永久”存在,即只要程序运行即可。 So, the memory occupied by "Some text!!" 因此, "Some text!!"占用的内存"Some text!!" is never released. 永远不会被释放。

Just keep in mind (as a side note) that string literals are non-modifyable objects. 只需记住(作为补充说明)字符串文字是不可修改的对象。 It is illegal to write into that memory. 写入该内存是非法的。

String will be stored statically in special (usually read-only on modern OS) section of the program binary. 字符串将静态存储在程序二进制文件的特殊部分(通常在现代OS中为只读)。 Its memory is not allocated (individually for the string, only for total section while loading it to memory) and will not be deallocated. 它的内存未分配(单独为字符串分配,仅在将其加载到内存时分配给整个段),并且不会被释放。

Will the memory pointed by retStr be occupied throughout the program or be released once the block A exits? retStr指向的内存是在整个程序中占用还是在块A退出后释放?

Edit: 编辑:

It will be not released, but retStr will not be available. 这将是没有公布,但retStr将不可用。 (block scope) (块范围)

const char *ptr;
{   
   const char* retStr = "Scope";
   ptr = retStr;
}   

printf("%s\n", ptr); //prints "Scope"

//printf("%s\n", retStr); //will throw error "retStr undeclared"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM