Question about & operator in C ++
I am looking at the .h file of the Wrapper class. And the class contains one private member:
T* dataPtr;
(where T
matches the template < class T >
one listed at the top of the .h file)
The class provides two "* operator overloading" methods:
T& operator*()
{
return *dataPtr;
}
const T& operator*() const
{
return *dataPtr;
}
Both just return *dataPtr
, but what does the letter " *dataPtr
" mean in plain English? And how does it match the return type " T&
"?
a source to share
dataPtr is a pointer to something.
The * operator looks for a pointer, so * dataPtr (or, instead of 'is', you can say 'refer to' or 'is reference to') pointee, that is, the thing that dataPtr points to.
T & means "a reference to an object of type T" (not to be confused with T *, which means "a pointer to an object of type T").
a source to share
*DataPtr
- the actual data to which it points DataPtr
. Both operators return a reference to T
. A reference is a type that you have to think of a different name for the value it refers to. Under the hood, it looks like a pointer, but don't think of it that way. It cannot do pointing math or be "re-enabled". One of the operators is const
and is used for an object const
, and the other is for an ordinary object.
a source to share
The wrapper class seems to act like a C ++ pointer.
The * operator allocates a wrapper that will evaluate the item it stores (in dataPtr). What you get is a link to this content. For instance. you can assign something to the link
*intWrapper = 42;
There are two operators as there is a constant and a non-constant version. When you go looking for a constant wrapper class, you cannot assign to it (constant reference (T &) is returned)
a source to share