Why is it ok to assign a std::string& to a std::string variable in c++?

class MyClass:
public:
   MyClass(const std::string& my_str);
private:
  std::string _myStr

In the implementation:

MyClass::MyClass(const std::string& my_str):
   _mystr(my_str)

How can you assign a reference (my_str is const std::string&) to a non-reference variable (_mystr, which is std::string) ?

In my mental model, a variable is a block of space in memory can be filled with stuff that is the same type as the variable’s declared type. So a std::string variable is a block of space that can hold a string (eg: "abcd"), while a const std::string& is a block of space in memory that can hold a "reference" (kind of vague what it is, unlike a pointer which is an address to another block in memory). When you assign one variable to another, you are copying the content stored in one memory block into another. So how can you copy a std::string& into a std::string – their types are different.

What am I mis-understanding here?

>Solution :

In your case you do not make an assignment actually.
This line:

_mystr(my_str)

Is involing the copy contructor of your _mystr member.
The copy contstructor received a const std::string& (my_str in your case), and constructs a clone of the object it refernces into your member _mystr.

But to answer your question in a more general way:
It is possible to assign a variable of type refernce into a non refernce type.
What will happen is the the assignment operator of the target will be invoked.
The assignment operator (of std::string in this case) accepts (like the copy constructor) a const std::string&, and assigns a clone of the object it refernces into your member _mystr.
Therefor this will work as well:

void f(std::string const & str)
{
   std::string local_str = str;
   // ...
}

All the above is correct in general for all classes.
Non-class types behaves in a similar manner, e.g.:

int i1;
int & ri1 = i1;
int i2 = ri1;  // Will assign a copy of the value refernces by ri1, i.e. the value of i1 into i2

See more here about Initialisation and assignment.
And Why are initialization lists preferred over assignments?.

Leave a Reply