Is get() reliable when an auto_ptr is uninitialized?
Asked Answered
A

3

6

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.?

Angora answered 23/8, 2016 at 13:42 Comment(1)
In this example, auto_ptr is not "uninitialized". The default constructor initializes the pointer to a null pointer.Autogenous
U
1

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.

Upstanding answered 24/8, 2016 at 9:11 Comment(0)
R
11

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.

Redstart answered 23/8, 2016 at 13:47 Comment(0)
F
3

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.

Freer answered 23/8, 2016 at 13:50 Comment(2)
When working with multiple platforms, can I rely on the default constructor (without having to check every implementation) or should I explicitly call reset(0) to be sure ?Angora
No, there is no need to call reset explicitly after the default ctor.Freer
U
1

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.

Upstanding answered 24/8, 2016 at 9:11 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.