passing a noncopyable class

I am reading a book and the author has a noncopyable class which ends up as a member variable of another class. It stuck out to me, because of the way the author did it and because he preferred a pointer to a reference. Let me give an example.

1
2
3
4
5
6
7
8
9
10
class Integer;         // noncopyable
class WrapperInteger
{
public:
	explicit	WrapperInteger(Integer& x)
			: mInteger(&x)
			{}

	Integer*	mInteger;
};


What the author did that surprised me was he passed the Integer object by reference and then he takes the address of the object and contructs mInteger pointer. Why start with a reference to end with a pointer?

1
2
3
4
5
6
7
8
9
10
11
class Integer;         // noncopyable
class WrapperInteger
{
public:

	explicit	WrapperInteger(Integer* x)
			: mInteger(x)
			{}

	Integer*	mInteger;
};


If I wanted a pointer this seems more straightforward (and identical). I do understand this may just be preference.

1
2
3
4
5
6
7
8
9
10
class Integer;         // noncopyable
class WrapperInteger
{
public:
	explicit	WrapperInteger(Integer& x)
				: mInteger(x)
				{}

	Integer&	mInteger;
};


Further, I've read to prefer references to pointers, so why not this?


Are all these examples accomplishing the same task? Also, why might the author prefer a pointer over a reference? Finally, is there a name for this usage?
The basic idea is to have a wrapper that can be used like a reference. While a normal reference will always refer to the same object, a wrapped reference simulates a reference that can be rebound to refer to a different object. To simulate a copyable, assignable wrapper, internally a non-null pointer is held; pointers are copyable and assignable.


> is there a name for this usage?

The is a name, and also a standard implementation of reference wrapper: std::reference_wrapper<>
http://en.cppreference.com/w/cpp/utility/functional/reference_wrapper

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
#include <iostream>
#include <functional>

struct non_copyable_class
{
    non_copyable_class( int i = 0 ) : x(i) {}
    non_copyable_class( const non_copyable_class& ) = delete ;
    non_copyable_class( non_copyable_class&& ) = delete ;

    int x ;
};

void foo( std::reference_wrapper<non_copyable_class> w )
{
    std::cout << w.get().x << ' ' << &w.get() << '\n' ;
}


int main()
{
   non_copyable_class nc(1234) ;

   std::reference_wrapper<non_copyable_class> wrapper(nc) ;
   std::cout << &nc << ' ' << &wrapper.get() << '\n' ;
   foo(nc) ;

   non_copyable_class nc2(99) ;
   wrapper = nc2 ; // now wraps nc2
   std::cout << &nc2 << ' ' << &wrapper.get() << '\n' ;
}

http://coliru.stacked-crooked.com/a/9247494c045108a3
Topic archived. No new replies allowed.