简体   繁体   中英

Declaring a reference to object and the assignment operator

I feel like this question is basic enough to be out there somewhere, but I can't seem to be able to find an answer for it.

Suppose I have this code:

//class member function
std::map< std::string, std::string > myMap;

const std::map< std::string, std::string >& bar()
{
   return myMap;
}

void myFunc( std::map< std::string, std::string >& foo1 )
{
   foo1 = bar();
   std::map< std::string, std::string >& foo2 = bar();
}

My understanding is that if I start using foo2, since foo2 is a reference to the same instance as what bar() returns, anything I do with foo2 will be reflected in myMap. But what about foo1? Does foo1 get a copy of myMap or does it also point to the same instance as what bar() returns? The c++ standard library says that the assignment operator for std::map will copy the elements over, but then does that mean the assignment operator is not really invoked in the declaration of foo2?

Thanks!

References are not reseatable in C++. This means that once they're initialized, you can't reassign them. Instead, any assignment actually involve the referred object. So in your code,

foo1 = bar();
std::map< std::string, std::string >& foo2 = bar();

the first line calls std::map::operator= on the object that was passed as a parameter to myFunc . After that, foo1 stills refers to that same object -- but its value (eg what elements it holds) may very well has been changed.

Note that the second line is not assignment if there ever was any doubt that it was in your mind. Instead, it is an initialization. Since the return type of bar is actually std::map<std::string, std::string> const& , it can't bind to std::map<std::string, std::string>& so it's a compile error.


To expand on the 'philosophical' side of things, C++ references are designed to be as transparent as possible and don't really exist as objects. This is using the C++ Standard meaning of the term (it is not related to OOP): it means that for instance reference types do not have a size. Instead, sizeof(T&) == sizeof(T) . Similarly, references do not have addresses and it's not possible to form a pointer or a reference to a reference: given int& ref = i; , then &ref == &i .

References are thus purposefully meant to be used as if the referred objects were being used themselves. The only thing reference-specific that happens in the lifetime of a reference is its initialization: what it can bind to and what it means in terms of lifetime.

The line

foo1 = bar();

creates a copy (because that's what map 's assignment operator does).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM