What happens when assigning a string literal to a member const char* variable from a constructor in C++?


gurga durgan

I've seen a few things on these lines lately, and after a lot of searching, I haven't found an answer that directly addresses this issue.

If I have the following code:

class Foo {
    const char *some_string;

    Foo()
    {
        some_string = "StringLiteral";
    }
};

Does this work?

The source is pretty well known, so my best guess is that this is acceptable and the behavior is defined.

My problem is that the memory that looks like the string literal is being used should be allocated on the stack and that memory should no longer be valid outside the scope of the constructor.

With this in mind, the best answer I can get is that the compiler puts the string into static memory, which means it's still valid outside the scope of this function.

However, like I said, none of the answers I've seen refer directly to string literals assigned directly from inside the function.

So, does this work? and why

songyuanyao

So, does this work? and why

Yes, it works. Because a string literal has static storage duration, it doesn't matter where it appears (in the body of a function or not).

String literals have static storage duration and therefore exist in memory for the lifetime of the program.

Related


Return const char* from string literal in C++?

Bernard Typically, I would return a std::stringfrom a function , because returning a const char*would require the caller to provide an output memory buffer, which is not resizable. But const char*does it work if it is returned from a string literal ? const cha

Return const char* from string literal in C++?

Bernard Typically, I would return a std::stringfrom a function because returning a const char*would require the caller to provide an output memory buffer, which is not resizable. But const char*does it work if it is returned from a string literal ? const char*

Return const char* from string literal in C++?

Bernard Typically, I would return a std::stringfrom a function because returning a const char*would require the caller to provide an output memory buffer, which is not resizable. But const char*does it work if it is returned from a string literal ? const char*