Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inserting addresses into sets, the size of the sets is smaller than expected

Tags:

c++

set

I am getting a size of 1. Shouldn't it be 4? I am inserting the addresses of integers into the sets.

void func(set<int*>& s1, set<int*>& s2, int a) {     s1.insert(&a);     s2.insert(&a); }  int main() {     set<int*> s1, s2;      int a = 1, b = 2, c = 3, d = 4;     func(s1, s2, a);     func(s1, s2, b);     func(s1, s2, c);     func(s1, s2, d);      cout<<"  s1.size = "<<s1.size()<<"  s2.size = "<<s2.size()<<endl; } 
like image 400
instance Avatar asked Jul 05 '17 06:07

instance


1 Answers

&a inside func is the address of the local parameter a, not the address of the original variable (a, b, c or d), which:

  1. Can take various kind of values between different calls of func;
  2. Becomes an invalid pointer once you reach the end of the scope in which a is declared (the end of func here).

In your case, since you do nothing but calling func 4 times in a row, the address of this parameter happens to not change, which is why you get a size of 1 (you insert the same pointer 4 times).

This behavior is implementation defined (thanks @Rakete1111) since sets will need to compare invalid pointers.

Accessing the pointed element through s1 or s2 (e.g. **s1.begin()) is undefined behavior though.

like image 98
Holt Avatar answered Oct 05 '22 11:10

Holt