Home > Enterprise >  What's the point of having a constructor with a default argument that takes a user-defined type
What's the point of having a constructor with a default argument that takes a user-defined type

Time:11-25

Ok so I'm trying to reimplement the Vector class from the STL. Here's a small chunk of the Template Class that includes a simple typedef for the Allocator passed as an argument.

template<typename T, typename Allocator = std::allocator<T>>
class vector {
public:
    typedef Allocator                                   allocator_type;
    // Other typedefs...
}

Simple enough, however, I just can't wrap my head around this constructor:

explicit vector(const allocator_type &alloc = allocator_type());

What is allocator_type() referring to? Is it the typedef? Is this some kind of function call? Is it even possible to pass a user-defined type here? I'm probably just missing something.

CodePudding user response:

Yes, it's the typedef.

The class template parameter Allocator has a default type, std::allocator<T>. If that is used or not isn't important. What is important is that whatever type Allocator is, it gets a type alias in form of allocator_type.

The constructor has a default value which is a default constructed allocator_type (whatever type that is). You could supply an instance of an allocator_type (possibly not default constructed) to the constructor and it would use that instead.

CodePudding user response:

The allocator_type is an alias for the Allocator. They mean the same thing but Allocator is only visible to members of the class, so the alias is required to make it public.

The constructor you've found would be an equivalent to:

explicit vector(const Allocator &alloc = Allocator());

except this notation is more confusing to the user of the class who can only use the name allocator_type in their code.

= allocator_type() just tells the compiler that it is an optional argument. If the user don't provide any other allocator_type object to the constructor of the vector, the default constructor of the Allocator/allocator_type will be used to create an object to be passed there instead.

CodePudding user response:

To answer the underlying question: what's the point of this constructor? It's a special kind of default constructor. SFINAE (Subsitution Failure Is Not An Error) means that this is not a default constructor for vector when Allocator is not default-constructible. It's still usable as a normal constructor, though.

  • Related