So I want to use a list for a part of my program. I'm trying to get acquainted to the library list, so I wrote a quick little program to help myself understand what's going on. It all works properly, but there's one thing I don't understand.
According to this: http://www.cplusplus.com/reference/list/list/front/ The return type for the front function should be a reference of the type (in this case, room) of the first element (the only element in this case).
But I was able to access the values without having to reference, because it seems that all the values were passed directly (not by reference). Is this expected? Is the website wrong? Is my compiler wrong (CodeBlocks 13.12)?
Here's my code:
#include <iostream>
#include <list>
using namespace std;
struct room {
int content;
struct room * north;
struct room * south;
struct room * east;
struct room * west;
} ;
int main ()
{
list<room> mylist;
cout << ( mylist.empty() ? "List is empty.\n" : "List is not empty.\n" ) << endl;
room * room1 = new room;
room1->content = 15;
cout
<< room1->content << "\n"
<< room1->north << "\n"
<< room1->south << "\n"
<< room1->east << "\n"
<< room1->west << "\n";
cout << "\n" << room1 << endl;
mylist.push_front(*room1);
cout << ( mylist.empty() ? "\nList is empty.\n" : "\nList is not empty.\n" ) << endl;
delete room1;
room test_room = mylist.front();
cout
<< test_room.content << "\n"
<< test_room.north << "\n"
<< test_room.south << "\n"
<< test_room.east << "\n"
<< test_room.west << "\n";
cout << "\n" << &test_room << endl;
return 0;
}
There are two types of constructors added automatically to any class you declare: The default constructor, which default-initializes all members of that class
§12.1.4and the copy constructor§12.8.7.In your case, we have to take a look at the copy constructor:
The declaration of the copy constructor looks like this (if you would write it down specifically
§12.8.8):As you can see, it takes a
constreference to anotherroomand initilizes all values of itself by copying from the passed inroom.The first thing that happens is that the list adds a copy of the
roomyou passed intomylist.push_front(*room1)(you can see thatpush_front()takes elements by const-ref§23.3.5.4but internally copies them. To do this, the copy-constructor is called the first time.When you later access the element with
mylist.front()it returns a reference but because you initialize a value ofroom, instead of a reference -room test_room = mylist.front();- the copy-constructor is invoked a second time. To correctly capture the front of the list by reference you need to doroom& test_room = mylist.front();.Note: All
§nbrrefer to the according section in the C++ standard.