Bo Persson wrote:
Salt_Peter wrote:
shuisheng wrote:
shuisheng wrote:
Dear All,
I find in std::auto_ptr, the private member is define as
template<class _Ty>
class auto_ptr
{
...
private:
const _Ty *_Myptr;
}
what is the meaning of const _Ty *_Myptr; in a class member
decalration?
I appreicate your kind help!
Shuisheng
To make my question more clear. I am thinking that the 'const'
qualifier should not be here because in auto_ptr, such as reset,
its content is changed. Where is my wrong?
Thanks.
Its not a constant pointer, its a mutable pointer to a constant
variable (see Kai-Uwe's Post).
Its contents are not changed during a reset(). Its given ownership
of an entirely new object (which deletes the old object, if any).
Reseating the pointer is not prohibited.
It is kind of interesting though, that an auto_ptr implementation stores a
pointer-to-const. We are still able to assign to the underlying element
using auto_ptr::operator*().
An implementation detail, I know, but still surprising.
Ok, but most don't store a ptr_to_constant. What is really strange with
auto_ptrs is that both the copy ctor and the assignment operator modify
a non-constant rvalue which renders the resulting rvalue into a nullptr
(transfer of ownership).
template< class T >
class auto_ptr {
...
autoptr( auto_ptr< T >& copy ) { ... } // non-const copy is modified
...
};
And a reference can result in a transfer of ownership:
#include <iostream>
#include <ostream>
#include <memory>
void foo(std::auto_ptr< int >& r_ap)
{
std::auto_ptr< int p_local(r_ap);
std::cout << *r_ap << std::endl; // error !!!
}
int main()
{
std::auto_ptr< int p_n(new int(5));
foo(p_n);
std::cout << *p_n << std::endl; // error !!!
}
Fortunately, a const ref to auto_ptr<Tsolves that issue.
With respect of its shortcomings (ie: not copyable and can't support
arrays) its a far, far better alternative than new/delete where
appropriate.