Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to test whether auto pointer is null?

Tags:

c++

auto-ptr

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.

like image 878
user853069 Avatar asked Aug 15 '11 20:08

user853069


People also ask

How do I check if a pointer is null?

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.

Is null and nullptr the same?

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.

How do you check if something is null in C++?

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.

WHAT IS null pointer in C++?

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.


2 Answers

When checking an std::auto_ptr for NULL, I think this is most idiomatic notation:

if (!myPointer.get()) {
    // do not dereference here
}
like image 101
Wolf Avatar answered Oct 21 '22 00:10

Wolf


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.

like image 42
Lightness Races in Orbit Avatar answered Oct 21 '22 00:10

Lightness Races in Orbit