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

Cody Gray - on strike
  • 239,200
  • 50
  • 490
  • 574
Marc
  • 856
  • 1
  • 8
  • 20

3 Answers3

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.

Holt
  • 36,600
  • 7
  • 92
  • 139
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.

Ami Tavory
  • 74,578
  • 11
  • 141
  • 185
  • 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 ? – Marc Aug 23 '16 at 14:13
  • 1
    No, there is no need to call `reset` explicitly after the default ctor. – Ami Tavory Aug 23 '16 at 14:13
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.

ComicSansMS
  • 51,484
  • 14
  • 155
  • 166