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