Reputation: 2069
Consider below code,
void handleConnection(Connection &connection) {
// std::vector
auto messages = connection->messages;
// Do Work
messages.clear();
}
Why does assigning connection->messages
to auto messages
creates a copy without implicitly creating a reference?
The main reason I asked this question is because I noted the above code causing duplicate messages and that means it makes a copy, but I cannot find a law in the C ++ standard that describes this.
Upvotes: 0
Views: 117
Reputation: 60208
The rules for auto state that the following code:
auto x = y;
will always make a copy of y
, and deduce the type of x
to be the same as y
. Whether y
is a member of an object that you're holding a reference to, is completely irrelevant.
Similarly,
auto &x = y;
will make x
a reference to y
, with the same type. Whether y
is a member of an object of which you have a copy or a reference, doesn't affect this at all.
Upvotes: 3