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
MyClasssucceeded, or an exception was thrown and theauto_ptrwill no longer be in scope. So, in the example you provided, the value of the pointer represented by yourauto_ptrcannot beNULL.(It is possible that you are using an implementation without exception support, that can return
NULLon 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_ptrdoes not have anoperator==.To do this, use
X* std::auto_ptr<X>::get() const throw(), like this:Also note that
std::auto_ptris deprecated in C++0x, in favour ofstd::unique_ptr. Prefer the latter where you have access to a conforming implementation.