Skip to content

Instantly share code, notes, and snippets.

@tansey
Created November 9, 2016 02:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tansey/359b59592f405e99a850f0daa0025bfd to your computer and use it in GitHub Desktop.
Save tansey/359b59592f405e99a850f0daa0025bfd to your computer and use it in GitHub Desktop.
terrible STL set iterator behavior
#include <set>
#include <iostream>
class A
{
std::set<int> s;
public:
A() { s.insert(0); s.insert(1); }
std::set<int> getSet() { return s; }
};
int main(void)
{
A a;
std::cout << "A contains " << a.getSet().size() << " elements. They are listed below:" << std::endl;
for (std::set<int>::const_iterator it = a.getSet().begin(); it != a.getSet().end(); ++it){
std::cout << *it << std::endl;
}
return 0;
}
@tansey
Copy link
Author

tansey commented Nov 9, 2016

Expected output:

A contains 2 elements. They are listed below:
0
1

Actual output:

A contains 2 elements. They are listed below:
0
Segmentation fault: 11

The issue seems to be that I'm returning a set by value. However, that is the recommended style since STL containers are shallow copied. In the case of set, it seems that it causes weird behavior.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment