nothrow_swap.cpp 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. // Boost.Function library
  2. // Copyright Douglas Gregor 2008. Use, modification and
  3. // distribution is subject to the Boost Software License, Version
  4. // 1.0. (See accompanying file LICENSE_1_0.txt or copy at
  5. // http://www.boost.org/LICENSE_1_0.txt)
  6. // For more information, see http://www.boost.org
  7. #include <boost/function.hpp>
  8. #include <boost/core/lightweight_test.hpp>
  9. #define BOOST_CHECK BOOST_TEST
  10. struct tried_to_copy { };
  11. struct MaybeThrowOnCopy {
  12. MaybeThrowOnCopy(int value = 0) : value(value) { }
  13. MaybeThrowOnCopy(const MaybeThrowOnCopy& other) : value(other.value) {
  14. if (throwOnCopy)
  15. throw tried_to_copy();
  16. }
  17. MaybeThrowOnCopy& operator=(const MaybeThrowOnCopy& other) {
  18. if (throwOnCopy)
  19. throw tried_to_copy();
  20. value = other.value;
  21. return *this;
  22. }
  23. int operator()() { return value; }
  24. int value;
  25. // Make sure that this function object doesn't trigger the
  26. // small-object optimization in Function.
  27. float padding[100];
  28. static bool throwOnCopy;
  29. };
  30. bool MaybeThrowOnCopy::throwOnCopy = false;
  31. int main()
  32. {
  33. boost::function0<int> f;
  34. boost::function0<int> g;
  35. MaybeThrowOnCopy::throwOnCopy = false;
  36. f = MaybeThrowOnCopy(1);
  37. g = MaybeThrowOnCopy(2);
  38. BOOST_CHECK(f() == 1);
  39. BOOST_CHECK(g() == 2);
  40. MaybeThrowOnCopy::throwOnCopy = true;
  41. f.swap(g);
  42. BOOST_CHECK(f() == 2);
  43. BOOST_CHECK(g() == 1);
  44. return boost::report_errors();
  45. }