Consider the following code:
std::auto_ptr<std::string> p;
if (p.get() == 0) {
...
}
Is the get()
member function a standard and reliable way for checking that p
has not been initialized? Will it always return 0, irrespective of the platform, compiler, compiler's optimization flags, etc.?
There is no such thing as un uninitialized std::auto_ptr
, the default constructor initializes the pointer to 0
:
explicit auto_ptr( X* p = 0 );
Thus get()
will effectively returns "0
" on a default constructed std::auto_ptr
.
The line
std::auto_ptr<std::string> p;
calls the constructor
explicit auto_ptr (X* p=0) throw();
which initializes the internal pointer to 0.
It depends, therefore, what you mean by "has not been initialized". Calling the default ctor, as you showed, will yield a get
that returns 0. Also initializing it to something else, followed by a call to reset(0)
, will yield a get
that returns 0.
The get
method of auto_ptr
has no preconditions.
That means, it is always safe to call that method, regardless of what state the auto_ptr
object is in.
Contrast this with the operator*
member function, which does have a precondition of get() != 0
. The C++ Standard specifies preconditions for member functions in a Requires clause. If no such clause is present for a function, it is always safe to call.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With