How to check if an auto pointer is null?

I am new to auto index. I have it:

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

How to check if I can create an instance of myPointer successfully? I tried if (myPointer==NULL) and the compiler threw an error:

no operator "==" matches these operands.

+8
c ++ auto-ptr
source share
5 answers

What do you mean by "instance"?

In a standard compatible implementation, either MyClass was built, or an exception was thrown, and auto_ptr would no longer be in scope. So, in the above example, the value of the pointer represented by your auto_ptr cannot be NULL .

(Perhaps you are using support without exception support, which can return NULL if the selection (nothrow) exception), even without using the (nothrow) , but this is not a common case.)


Generally speaking, you can check the value of a pointer. You just need to get a basic view, because as you discovered, std::auto_ptr does not have operator== .

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

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

Also note that std::auto_ptr deprecated in C ++ 0x, in favor of std::unique_ptr . Prefer the latter when you have access to the appropriate implementation.

+22
source share

How about this?

  if(myPointer.get()==NULL) 
+4
source share

I think myPointer.get() == NULL is what you are looking for.

+3
source share

Given the statement that you wrote in your question, either myPointer was installed, or an exception was thrown, and detecting an exception is the right way to verify that something went wrong.

In any case, you can get the base pointer by calling auto_ptr::get() .

+1
source share

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

 if (!myPointer.get()) { // do not dereference here } 
0
source share

All Articles