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.
You can usually check for NULL using ptr == 0, but there are corner cases where this can cause an issue. Perhaps more importantly, using NULL makes it obvious that you are working with pointers for other people reading your code.
nullptr is a keyword that can be used at all places where NULL is expected. Like NULL, nullptr is implicitly convertible and comparable to any pointer type. Unlike NULL, it is not implicitly convertible or comparable to integral types.
In C or C++, there is no special method for comparing NULL values. We can use if statements to check whether a variable is null or not.
A null pointer has a reserved value that is called a null pointer constant for indicating that the pointer does not point to any valid object or function. You can use null pointers in the following cases: Initialize pointers. Represent conditions such as the end of a list of unknown length.
When checking an std::auto_ptr
for NULL
, I think this is most idiomatic notation:
if (!myPointer.get()) {
// do not dereference here
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With