K
Keith Willis
Moving along from my experiments with auto_ptr, I threw together a
custom smart pointer template based on stuff I saw at the GOTW site.
It all works swimmingly, except when I need to pass the underlying
pointer to a function like memset() or whatever. The template has
overloads for operator->() and operator*() like this:
template <class T> class SmartPtr
{
<snip>
T& operator*() const
{ return *p_; }
T* operator->() const
{ return p_; }
<snip>
}
This is fine and I can access members using the normal p_->member
syntax. But what about when I want to pass the pointer to a function,
like this:
memset(p_, value, sizeof *p_);
This gives me an error complaining that it can't convert a
SmartPtr<whatever> to a void*. At present I've worked around it by
adding a method to the template which explicitly returns the address:
template <class T> class SmartPtr
{
<snip>
T& operator*() const
{ return *p_; }
T* operator->() const
{ return p_; }
T* Addr() const
{ return p_; }
<snip>
}
which lets me do:
memset(p_.Addr(), value, sizeof *p_);
Is this the only/best way around the problem?
custom smart pointer template based on stuff I saw at the GOTW site.
It all works swimmingly, except when I need to pass the underlying
pointer to a function like memset() or whatever. The template has
overloads for operator->() and operator*() like this:
template <class T> class SmartPtr
{
<snip>
T& operator*() const
{ return *p_; }
T* operator->() const
{ return p_; }
<snip>
}
This is fine and I can access members using the normal p_->member
syntax. But what about when I want to pass the pointer to a function,
like this:
memset(p_, value, sizeof *p_);
This gives me an error complaining that it can't convert a
SmartPtr<whatever> to a void*. At present I've worked around it by
adding a method to the template which explicitly returns the address:
template <class T> class SmartPtr
{
<snip>
T& operator*() const
{ return *p_; }
T* operator->() const
{ return p_; }
T* Addr() const
{ return p_; }
<snip>
}
which lets me do:
memset(p_.Addr(), value, sizeof *p_);
Is this the only/best way around the problem?