Is get() reliable when an auto_ptr is uninitialized?

282 Views Asked by At

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.?

3

There are 3 best solutions below

0
ComicSansMS On BEST ANSWER

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.

0
Holt On

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.

2
Ami Tavory On

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.