Trivial raw pointer that self-initializes to nullptr in C++
c++, c++11, pointers, unique-ptr
Solution
C++11 allows in class initialization of data members.
class foo
{
// ...
lar *pr = nullptr;
};
That'll always initialize `pr` to `nullptr` unless you assign another value in the constructor.
Problem
I like the new pointer types in C++11, but sometimes I still need a raw pointer. Something that makes me increasingly sad about "raw" types in C++, however, is their habit of initializing as undefined when not given an explicit value. As I use std::shared_ptr<> and the like more often, this need to initialize raw pointers to null feels increasingly brittle and unnecessary. I'm talking about: ``` class foo { ... std::shared_ptr< bar > pb; // Initially null in whatever constructor. std::unique_ptr< dar > pd; // Likewise. std::weak_ptr< gar > pg; // And again. lar* pr; // Uh-oh! Who knows what this is? Better remember to initialize... }; foo::foo( int j ) : pr( nullptr ) {...} foo::foo( const string& s ) : pr( nullptr ) {...} ... etc.: many tedious and error-prone constructor definitions follow. ``` What I'd like, therefore, is a "raw pointer with null initialization." Something like: ``` class foo { ... std::shared_ptr< bar > pb; // Initially null in whatever constructor. std::unique_ptr< dar > pd; // Likewise. std::weak_ptr< gar > pg; // And again. raw_ptr< lar > pr; // Once more with feeling. }; foo::foo( int j ) {...} // No explicit pointer initialization necessary. foo::foo( const string& s ) {...} ... ``` More precisely, what I want is a simple, cheap type that acts exactly like a raw pointer in every way except that its default constructor initializes it to nullptr. My question: (1) Does such a thing already exist in the standard library? (2) If not, what would be the most elegant/smallest way to accomplish an implementation of this type? P.S. I'm not interested in Boost or any other libraries, unless perhaps it is a header-only library in a single file. Smallness and simplicity are of the essence.