how to test whether auto pointer is null?

user853069 picture user853069 · Aug 15, 2011 · Viewed 18.1k times · Source

I'm new to auto pointer. I have this:

std::auto_ptr<myClass> myPointer(new MyClass(someArg));

How do I test whether I can instantiate myPointer successfully? I tried if (myPointer==NULL) and the compiler emitted an error:

no operator "==" matches these operands.

Answer

Lightness Races in Orbit picture Lightness Races in Orbit · Aug 15, 2011

What do you mean by "instantiate"?

On a standard-compliant implementation, either the construction of the MyClass succeeded, or an exception was thrown and the auto_ptr will no longer be in scope. So, in the example you provided, the value of the pointer represented by your auto_ptr cannot be NULL.

(It is possible that you are using an implementation without exception support, that can return NULL on allocation failure (instead of throwing an exception), even without the use of the (nothrow) specifier, but this is not the general case.)


Speaking generally, you can check the pointer's value. You just have to get at the underlying representation because, as you've discovered, std::auto_ptr does not have an operator==.

To do this, use X* std::auto_ptr<X>::get() const throw(), like this:

if (myPointer.get()) {
   // ...
}

Also note that std::auto_ptr is deprecated in C++0x, in favour of std::unique_ptr. Prefer the latter where you have access to a conforming implementation.