Ticket #9578: container_test.cpp

File container_test.cpp, 1.5 KB (added by Igor Lubashev <ilubashe@…>, 9 years ago)

Test to demonstrate undefined behavior of boost::range::adapter::map_keys when applied to an r-value and used with BOOST_FOREACH

Line 
1#include <iostream>
2
3#include <map>
4#include <string>
5
6#include <boost/foreach.hpp>
7#include <boost/range/adaptor/map.hpp>
8
9using namespace std;
10using namespace boost::adaptors;
11
12typedef map<string, string> my_map_t;
13
14my_map_t map_generator() {
15 cout << " Generating map" << endl;
16 my_map_t return_value;
17 return_value["igor!"] = "james";
18 return_value["12345"] = "ABCDE";
19 return_value["QWERT"] = "qwert";
20 return return_value;
21}
22
23void using_temp_ref(const my_map_t &my_map)
24{
25 BOOST_FOREACH(const string &key, my_map | map_keys) {
26 cout << "key = '" << key << "'" << endl;
27 }
28}
29
30template <typename T>
31void using_range_iterator(const boost::iterator_range<T> &keys_range)
32{
33 BOOST_FOREACH(const string &key, keys_range) {
34 cout << "key = '" << key << "'" << endl;
35 }
36}
37
38
39int main(int argc, char** argv) {
40 cout << "Test #1 (local variable)" << endl;
41 my_map_t m = map_generator();
42 BOOST_FOREACH(const string &key, m | map_keys) {
43 cout << "key = '" << key << "'" << endl;
44 }
45
46 cout << "Test #2 (value_type)" << endl;
47 BOOST_FOREACH(const my_map_t::value_type& p, map_generator()) {
48 cout << "key = '" << p.first << "'" << endl;
49 }
50
51 cout << "Test #3 (temp ref)" << endl;
52 using_temp_ref(map_generator());
53
54 cout << "Test #4 (range_iterator)" << endl;
55 using_range_iterator(map_generator() | map_keys);
56
57 cout << "Test #5 (bug)" << endl;
58 BOOST_FOREACH(const string &key, map_generator() | map_keys) {
59 cout << "key = '" << key << "'" << endl;
60 }
61
62 cout << "Test passed!" << endl;
63}