This is a very specific issue and is a bit long to explain, so please bear with me as I try to summarize this as best I can.
I create 2 user types, the first is used inside the second :
struct mySubType {
int val;
mySubType () {}
mySubType ( int _val) : val(_val){}
bool operator!=(const mySubType& rhs) const { return val != rhs.val; }
};
struct myType {
mySubType start;
mySubType stop;
myType () {}
myType (mySubType _start, mySubType _stop) : start(_start), stop(_stop) {}
};
In main()
, I create a vector
of unique_ptr
to myType
and fill it as such :
vector<unique_ptr<myType>> v;
for (int i = 0; i < 10; ++i)
v.push_back( unique_ptr<myType>(new myType( mySubType(i), mySubType(i+1))) );
So the val
of start
and stop
for each element is as follows :
start:0 stop:1
start:1 stop:2
start:2 stop:3
start:3 stop:4
start:4 stop:5
start:5 stop:6
start:6 stop:7
start:7 stop:8
start:8 stop:9
start:9 stop:10
start
should always be the same as previous stop
(this is the case in this example). To check this, I tried the following :
for (auto it = v.begin(); it != --v.end(); )
{
if ((*it)->stop != (*(++it))->start)
cout << "1";
}
To my surprise, the output was : 111111111
, all different when they should be all equal.
I tried a few other things to try and understand the source of the error. I replaced the inside of the loop with
mySubType stop = (*it)->stop;
mySubType next_start = (*(++it))->start;
if (stop != next_start)
cout << "2";
and then
if ((*it)->stop.val != (*(++it))->start.val)
cout << "3";
Neither of those printed anything (all tests were correctly solved as equal).
This only happens when using unique_ptr
(vector<myType>
does not have the same issue). I also tried using post-increment but I get the exact same result.
Does anyone have a clue why this happens ?
I know there are a lot of ways to work around this issue (the 2 above for example). What I'm interested in is why this behaviour happens.