Convert char * to string &

I have the following code:

#include <iostream> using namespace std; int main(int argc, char *argv[]) { string &s1 = argv[0]; // error const string &s2 = argv[0]; // ok argv[0] = "abc"; cout << argv[0] << endl; // prints "abc" cout << s2 << endl; // prints program name } 

I get the following error for s1 :

 invalid initialization of reference of type 'std::string& {aka std::basic_string<char>&}' from expression of type 'char*' 

Then why does the compiler accept s2 ?

Interestingly, when I assign a new value to argv[0] , s2 does not change. Does the compiler ignore that this is a link and copy the value anyway? Why is this happening?

I write this in Code :: Blocks 16.01 (mingw). The same thing happens with / without -std=c++11 .

+5
source share
4 answers

Then why does the compiler accept s2?

Since a permalink can bind to a temporary one, and std::string has a constructor that can accept char * for a parameter.

This assignment creates a so-called "temporary" object and associates a permalink with it.

Interestingly, when I assign a new value to argv [0], s2 is not a change.

Why should this change? s2 is a separate entity. The std::string object does not support the pointer to the char * that created it. There are many ways to create std::string . The actual string belongs to the object. If std::string constructed from an alphabetic character string, it is copied to std::string . So, if a literal string of characters comes from the buffer, and then the buffer is modified, this does not affect std::string .

+6
source

This line:

 const string &s2 = argv[0]; 

Creates a new instance of string , copying the contents of argv[0] and linking the link to it. This copy is later issued, which is now unrelated to the actual value of argv[0] .

The temporary string space of objects created in the quoted string expands to the block volume, since a link to the constant was created for it. See More at: Does the Constant Reference Contain a Temporary Lifetime?

+5
source

In both cases, the code asks the compiler to build a temporary std::string object whose contents are a copy of argv[0] . Although it is fun and perhaps useful to look at the details of what works, and why, in terms of writing code, messing up with temporary ones is not necessary and leads to confusion. Just create an object:

 std::string s1 = argv[0]; 
+1
source

Line

 const string &s2 = argv[0]; 

equally:

 const string &s2 = std::string(argv[0]); 

So, s2 contains a const reference to a temporary line that copied the contents from argv [0].

+1
source

All Articles