doc_move_return.cpp 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. //////////////////////////////////////////////////////////////////////////////
  2. //
  3. // (C) Copyright Ion Gaztanaga 2014-2014.
  4. // Distributed under the Boost Software License, Version 1.0.
  5. // (See accompanying file LICENSE_1_0.txt or copy at
  6. // http://www.boost.org/LICENSE_1_0.txt)
  7. //
  8. // See http://www.boost.org/libs/move for documentation.
  9. //
  10. //////////////////////////////////////////////////////////////////////////////
  11. #include <boost/move/detail/config_begin.hpp>
  12. //[move_return_example
  13. #include "movable.hpp"
  14. #include "copymovable.hpp"
  15. #include <boost/move/core.hpp>
  16. template<class Type>
  17. struct factory_functor
  18. {
  19. typedef Type return_type;
  20. Type operator()() const
  21. { Type t; return BOOST_MOVE_RET(Type, t); }
  22. };
  23. struct return_reference
  24. {
  25. typedef non_copy_movable &return_type;
  26. non_copy_movable &operator()() const
  27. { return ncm; }
  28. static non_copy_movable ncm;
  29. };
  30. non_copy_movable return_reference::ncm;
  31. //A wrapper that locks a mutex while the
  32. //factory creates a new value.
  33. //It must generically move the return value
  34. //if possible both in C++03 and C++11
  35. template <class Factory>
  36. typename Factory::return_type lock_wrapper(Factory f)
  37. {
  38. typedef typename Factory::return_type return_type;
  39. //LOCK();
  40. return_type r = f();
  41. //UNLOCK();
  42. //In C++03: boost::move() if R is not a reference and
  43. //has move emulation enabled. In C++11: just return r.
  44. return BOOST_MOVE_RET(return_type, r);
  45. }
  46. int main()
  47. {
  48. movable m = lock_wrapper(factory_functor<movable> ());
  49. copy_movable cm = lock_wrapper(factory_functor<copy_movable>());
  50. copyable c = lock_wrapper(factory_functor<copyable> ());
  51. non_copy_movable &mr = lock_wrapper(return_reference ());
  52. //<-
  53. (void)m; (void)cm; (void)c; (void)mr;
  54. //->
  55. return 0;
  56. }
  57. //]
  58. #include <boost/move/detail/config_end.hpp>