Imported Upstream version 2.99.2
[platform/upstream/libsigc++.git] / tests / test_bind_ref.cc
1 #include "testutilities.h"
2 #include <sigc++/sigc++.h>
3 #include <sstream>
4 #include <string>
5 #include <functional> //For std::ref().
6 #include <cstdlib>
7
8 namespace
9 {
10 std::ostringstream result_stream;
11
12 class Param : public sigc::trackable
13 {
14 public:
15   Param(const std::string& name)
16   : name_(name)
17   {}
18
19   //non-copyable,
20   //so it can only be used with sigc::bind() via sigc::ref()
21   Param(const Param&) = delete;
22   Param& operator=(const Param&) = delete;
23
24   //non movable:
25   Param(Param&&) = delete;
26   Param& operator=(Param&&) = delete;
27
28   std::string name_;
29 };
30
31 void handler(Param& param)
32 {
33   result_stream << "  handler(param): param.name_=" << param.name_;
34 }
35
36 } // end anonymous namespace
37
38 int main(int argc, char* argv[])
39 {
40   auto util = TestUtilities::get_instance();
41
42   if (!util->check_command_args(argc, argv))
43     return util->get_result_and_delete_instance() ? EXIT_SUCCESS : EXIT_FAILURE;
44
45   auto slot_full = sigc::ptr_fun(&handler);
46   sigc::slot<void()> slot_bound;
47
48   slot_bound();
49   util->check_result(result_stream, "");
50
51   {
52     //Because Param derives from sigc::trackable(), std::ref() should disconnect
53     // the signal handler when param is destroyed.
54     Param param("murrayc");
55     // A convoluted way to do
56     // slot_bound = sigc::bind(slot_full, std::ref(param));
57     slot_bound = sigc::bind< -1, decltype(slot_full), std::reference_wrapper<Param> >(slot_full, std::ref(param));
58
59     result_stream << "Calling slot when param exists:";
60     slot_bound();
61     util->check_result(result_stream,
62       "Calling slot when param exists:  handler(param): param.name_=murrayc");
63   } // auto-disconnect
64
65   result_stream << "Calling slot when param does not exist:";
66   slot_bound();
67   util->check_result(result_stream, "Calling slot when param does not exist:");
68   // This causes a crash when using g++ 3.3.4 or 3.3.5 (but not 3.4.x) when not specifying
69   // the exact template specialization in visit_each_type() - see the comments there.
70   // It looks like the auto-disconnect does not work, so the last slot_bound() call tries
71   // to access the param data again.
72
73   return util->get_result_and_delete_instance() ? EXIT_SUCCESS : EXIT_FAILURE;
74 }