1#include "../WeakCallback.h" 2 3#define BOOST_TEST_MAIN 4#ifdef BOOST_TEST_DYN_LINK 5#include <boost/test/unit_test.hpp> 6#else 7#include <boost/test/included/unit_test.hpp> 8#endif 9 10#include <stdio.h> 11#include <boost/noncopyable.hpp> 12 13class String 14{ 15 public: 16 String(const char* str) 17 { 18 printf("String ctor this %p\n", this); 19 } 20 21 String(const String& rhs) 22 { 23 printf("String copy ctor this %p, rhs %p\n", this, &rhs); 24 } 25 26 String(String&& rhs) 27 { 28 printf("String move ctor this %p, rhs %p\n", this, &rhs); 29 } 30}; 31 32class Foo : boost::noncopyable 33{ 34 public: 35 void zero(); 36 void zeroc() const; 37 void one(int); 38 void oner(int&); 39 void onec(int) const; 40 void oneString(const String& str); 41 void oneStringRR(String&& str); 42}; 43 44void Foo::zero() 45{ 46 printf("Foo::zero()\n"); 47} 48 49void Foo::zeroc() const 50{ 51 printf("Foo::zeroc()\n"); 52} 53 54void Foo::one(int x) 55{ 56 printf("Foo::one() x=%d\n", x); 57} 58 59void Foo::oner(int& x) 60{ 61 printf("Foo::oner() x=%d\n", x); 62 x = 1000; 63} 64 65void Foo::onec(int x) const 66{ 67 printf("Foo::onec() x=%d\n", x); 68} 69 70void Foo::oneString(const String& str) 71{ 72 printf("Foo::oneString\n"); 73} 74 75void Foo::oneStringRR(String&& str) 76{ 77 printf("Foo::oneStringRR\n"); 78} 79 80String getString() 81{ 82 return String("zz"); 83} 84 85BOOST_AUTO_TEST_CASE(testMove) 86{ 87 String s("xx"); 88 Foo f; 89 f.oneString(s); 90 f.oneString(String("yy")); 91 // f.oneStringRR(s); 92 f.oneStringRR(String("yy")); 93 f.oneString(getString()); 94 f.oneStringRR(getString()); 95} 96 97BOOST_AUTO_TEST_CASE(testWeakCallback) 98{ 99 printf("======== testWeakCallback \n"); 100 std::shared_ptr<Foo> foo(new Foo); 101 muduo::WeakCallback<Foo> cb0 = muduo::makeWeakCallback(foo, &Foo::zero); 102 muduo::WeakCallback<Foo> cb0c = muduo::makeWeakCallback(foo, &Foo::zeroc); 103 cb0(); 104 cb0c(); 105 106 muduo::WeakCallback<Foo, int> cb1 = muduo::makeWeakCallback(foo, &Foo::one); 107 auto cb1c = muduo::makeWeakCallback(foo, &Foo::onec); 108 auto cb1r = muduo::makeWeakCallback(foo, &Foo::oner); 109 cb1(123); 110 cb1c(234); 111 int i = 345; 112 cb1r(i); 113 BOOST_CHECK_EQUAL(i, 1000); 114 115 auto cb2 = muduo::makeWeakCallback(foo, &Foo::oneString); 116 auto cb2r = muduo::makeWeakCallback(foo, &Foo::oneStringRR); 117 printf("_Z%s\n", typeid(cb2).name()); 118 printf("_Z%s\n", typeid(cb2r).name()); 119 cb2(String("xx")); 120 cb2r(String("yy")); 121 122 muduo::WeakCallback<Foo> cb3(foo, std::bind(&Foo::oneString, std::placeholders::_1, "zz")); 123 124 cb3(); 125 126 printf("======== reset \n"); 127 foo.reset(); 128 cb0(); 129 cb0c(); 130 cb1(123); 131 cb1c(234); 132 cb2(String("xx")); 133 cb2r(String("yy")); 134 cb3(); 135} 136