Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Assigning a string literal to std::string

I am aware that the following code will create an array of characters and remain in memory until the program ends:

char* str = "this is a string";

As for this statement, creates a local array of characters and will be freed when str goes out of scope:

char str[] = "this is a string";

What I'm curious is, what happens when I write it like this:

std::string str = "this is a string";

str should make a copy of the string in it's own memory (local), but what about the string literal itself? Will it have the lifetime of the program or will it be freed when str goes out of scope?

like image 457
nancyheidilee Avatar asked Sep 05 '15 13:09

nancyheidilee


People also ask

Can we assign string to string in C++?

You can assign a C++ string object, a C string, or a C string literal to a C++ string object. Once again, this works because of operator overloading.

Is std::string literal?

std::string literals are Standard Library implementations of user-defined literals (see below) that are represented as "xyz"s (with a s suffix). This kind of string literal produces a temporary object of type std::string , std::wstring , std::u32string , or std::u16string , depending on the prefix that is specified.

How do you assign a string to a different string in C++?

std::string::assign() in C++ The member function assign() is used for the assignments, it assigns a new value to the string, replacing its current contents. Syntax 1: Assign the value of string str.


1 Answers

When you write this

std::string str = "this is a string";

C++ should find a constructor of std::string that takes const char*, calls it to make a temporary object, invokes the copy constructor to copy that temporary into str, and then destroys the temporary object.

However, there is an optimization that allows C++ compiler to skip construction and destruction of the temporary object, so the result is the same as

std::string str("this is a string");

but what about the string literal itself? Will it have the lifetime of the program or will it be freed when str goes out of scope?

String literal itself when used in this way is not accessible to your program. Typically, C++ places it in the same segment as other string literals, uses it to pass to the constructor of std::string, and forgets about it. The optimizer is allowed to eliminate duplicates among all string literals, including ones used only in the initialization of other objects.

like image 151
Sergey Kalinichenko Avatar answered Oct 13 '22 04:10

Sergey Kalinichenko