I was fiddling with various ways to handle data when I came across the following behavior that I don't understand. In reading the code below please pay attention to the variables firstDoubleIter and secondDoubleIter, in particular which elements of the (various copies) of the list they point to.
My question is below.
#include <list>
#include <iostream>
template <class T>
class MyListContainer
{
public:
std::list<T> list;
MyListContainer() : list() {;}
MyListContainer(const MyListContainer& container) : list(container.list) {;}
MyListContainer(std::list<T> list) : list(list) {;}
std::list<T> getList() const {return list;}
};
int main()
{
typedef MyListContainer<double> DoubleList;
DoubleList doubleContainer = DoubleList(std::list<double>({0, 1}));
auto firstDoubleIter = doubleContainer.getList().begin();
auto secondDoubleIter = ++(doubleContainer.getList().begin());
std::cout << "Using the getList() method\n";
std::cout << "*firstDoubleIter = " << *firstDoubleIter << "\n";
std::cout << "*secondDoubleIter = " << *secondDoubleIter << "\n";
std::list<double> listOfDoubles = doubleContainer.list;
firstDoubleIter = listOfDoubles.begin();
secondDoubleIter = ++listOfDoubles.begin();
std::cout << "Accessing the list directly\n";
std::cout << "*firstDoubleIter = " << *firstDoubleIter << "\n";
std::cout << "*secondDoubleIter = " << *secondDoubleIter << "\n";
}
Which produces the following output:
Using the getList() method
*firstDoubleIter = 1
*secondDoubleIter = 0
Accessing the list directly
*firstDoubleIter = 0
*secondDoubleIter = 1
My understanding is that the values for *firstDoubleIter and *secondDoubleIter should be the same even with the implicit list copy.
My question is: Why are they not the same?