File: doc_template_assign.cpp

package info (click to toggle)
boost1.83 1.83.0-5
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 545,632 kB
  • sloc: cpp: 3,857,086; xml: 125,552; ansic: 34,414; python: 25,887; asm: 5,276; sh: 4,799; ada: 1,681; makefile: 1,629; perl: 1,212; pascal: 1,139; sql: 810; yacc: 478; ruby: 102; lisp: 24; csh: 6
file content (95 lines) | stat: -rw-r--r-- 1,998 bytes parent folder | download | duplicates (7)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
//////////////////////////////////////////////////////////////////////////////
//
// (C) Copyright Ion Gaztanaga 2014-2014.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
//
// See http://www.boost.org/libs/move for documentation.
//
//////////////////////////////////////////////////////////////////////////////

#include <boost/move/detail/meta_utils_core.hpp>

#include <boost/move/move.hpp>

//[template_assign_example_foo_bar

class Foo
{
   BOOST_COPYABLE_AND_MOVABLE(Foo)

   public:
   int i;
   explicit Foo(int val)      : i(val)   {}

   Foo(BOOST_RV_REF(Foo) obj) : i(obj.i) {}

   Foo& operator=(BOOST_RV_REF(Foo) rhs)
   {  i = rhs.i; rhs.i = 0; return *this; }

   Foo& operator=(BOOST_COPY_ASSIGN_REF(Foo) rhs)
   {  i = rhs.i; return *this;   } //(1)

   template<class U> //(*) TEMPLATED ASSIGNMENT, potential problem
   //<-
   #if 1
   typename ::boost::move_detail::disable_if_same<U, Foo, Foo&>::type
   operator=(const U& rhs)
   #else
   //->
   Foo& operator=(const U& rhs)
   //<-
   #endif
   //->
   {  i = -rhs.i; return *this;  } //(2)
};
//]

struct Bar
{
   int i;
   explicit Bar(int val) : i(val) {}
};


//<-
#ifdef NDEBUG
#undef NDEBUG
#endif
//->
#include <cassert>

int main()
{
//[template_assign_example_main
   Foo foo1(1);
   //<-
   assert(foo1.i == 1);
   //->
   Foo foo2(2);
   //<-
   assert(foo2.i == 2);
   Bar bar(3);
   assert(bar.i == 3);
   //->
   foo2 = foo1; // Calls (1) in C++11 but (2) in C++98
   //<-
   assert(foo2.i == 1);
   assert(foo1.i == 1); //Fails in C++98 unless workaround is applied
   foo1 = bar;
   assert(foo1.i == -3);
   foo2 = boost::move(foo1);
   assert(foo1.i == 0);
   assert(foo2.i == -3);
   //->
   const Foo foo5(5);
   foo2 = foo5; // Calls (1) in C++11 but (2) in C++98
   //<-
   assert(foo2.i == 5); //Fails in C++98 unless workaround is applied
   assert(foo5.i == 5);
   //->
//]
   return 0;
}