c++c++03auto-ptr

Is get() reliable when an auto_ptr is uninitialized?


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


Solution

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