How long does a string constant live in C ++?

I was wondering how long the constant string has lived in C ++. For example, if I create a const char * str = "something" inside the function, would it be safe to return the value of str?

I wrote an example program and was really surprised to see that such a return value still stores this 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;
}

It gives me the following result:

I am a string

I am also a string

I am the default string

I am not the default string

10

The function of func3 is to find out if the same thing works with other types.
Therefore, the question arises: is it safe to return a pointer to the string constant created inside this function (as in func1 ())?
Also, is it safe to use the default string value, as in func2 ()?

+4
1

. ++ 2.14.5 , 8, ( ):

UTF-8 . "" of n const char ", n - , , (3.7).

3.7.1 1:

, , , . (3.6.2, 3.6.3).

func3 . , , . 12.2, :

- . 115, , , , , :

+10

Source: https://habr.com/ru/post/1548498/


All Articles