本文介绍了字符串常量在C ++中可以生存多长时间?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直想知道,字符串常量在C ++中可以生存多长时间.例如,如果我在函数内创建一些const char * str ="something",返回str的值是否安全?

I've been wondering, how long does a string constant live in C++. For example, if I create some const char *str = "something" inside a function, would it be safe to return the value of str?

我编写了一个示例程序,很惊讶地看到这样的返回值仍然存储了该字符串.这是代码:

I wrote a sample program and was really surprised to see that such returned value still stored that string. Here is the code:

#include <iostream>
using namespace std;

const char *func1()
{
    const char *c = "I am a string too";
    return c;
}

void func2(const char *c = "I'm a default string")
{
    cout << c << endl;
}

const int *func3()
{
    const int &b = 10;
    return &b;
}

int main()
{
    const char *c = "I'm a string";
    cout << c << endl;
    cout << func1() << endl;
    func2();
    func2("I'm not a default string");
    cout << *func3() << endl;
    return 0;
}

它给了我以下输出:

我也是一个字符串

我是默认字符串

我不是默认字符串

10

func3只是在查找是否可以与其他类型一起使用.
所以问题是:返回指向在该函数内创建的字符串常量的指针是否安全(如func1()一样)?
另外,使用func2()中的默认字符串值是否安全?

The func3 is there just to find out if the same works with other types.
So the question is: is it safe to return a pointer to a string constant created within that function (as in func1())?
Also, is it safe to use the default string value as in func2()?

推荐答案

字符串文字具有静态存储持续时间,并且可以延长程序的寿命.从草稿C ++标准部分2.14.5 字符串文字段落 8 说(强调我的前进):

A string literal has static storage duration and lasts the life of the program. From the draft C++ standard section 2.14.5 String literals paragraph 8 which says (emphasis mine going forward):

以及3.7.1 静态存储期限 1 段:

另一方面,func3中的第二种情况无效.引用的临时绑定的生存期在该引用的生存期内一直存在,在这种情况下,函数返回时将终止该生存期. 12.2部分对此进行了说明:

The second case in func3 on the other other hand is not valid. The lifetime of a temporary bound to a reference persists for the life of the reference, which in this case ends when the function returns. This is covered in section 12.2 which says:

这篇关于字符串常量在C ++中可以生存多长时间?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-31 02:34