Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is get() reliable when an auto_ptr is uninitialized?

Consider the following code:

std::auto_ptr<std::string> p;

if (p.get() == 0) {
   ...
}

Is the get() member function a standard and reliable way for checking that p has not been initialized? Will it always return 0, irrespective of the platform, compiler, compiler's optimization flags, etc.?

like image 448
Marc Avatar asked Aug 23 '16 13:08

Marc


3 Answers

There is no such thing as un uninitialized std::auto_ptr, the default constructor initializes the pointer to 0:

explicit auto_ptr( X* p = 0 );

Thus get() will effectively returns "0" on a default constructed std::auto_ptr.

like image 163
Holt Avatar answered Oct 16 '22 15:10

Holt


The line

std::auto_ptr<std::string> p;

calls the constructor

explicit auto_ptr (X* p=0) throw();

which initializes the internal pointer to 0.

It depends, therefore, what you mean by "has not been initialized". Calling the default ctor, as you showed, will yield a get that returns 0. Also initializing it to something else, followed by a call to reset(0), will yield a get that returns 0.

like image 38
Ami Tavory Avatar answered Oct 16 '22 15:10

Ami Tavory


The get method of auto_ptr has no preconditions.

That means, it is always safe to call that method, regardless of what state the auto_ptr object is in.

Contrast this with the operator* member function, which does have a precondition of get() != 0. The C++ Standard specifies preconditions for member functions in a Requires clause. If no such clause is present for a function, it is always safe to call.

like image 1
ComicSansMS Avatar answered Oct 16 '22 15:10

ComicSansMS