Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

why does allocator in c++ need a copy constructor?

Tags:

c++

stl

allocator

It is said here that it's because of exception specification. I do not understand it. Does this question have any relationship with exception specification?

like image 306
Xiaotian Pei Avatar asked Aug 21 '11 08:08

Xiaotian Pei


People also ask

Why do you need a copy constructor?

The copy constructor is used to initialize the members of a newly created object by copying the members of an already existing object. 2. Copy constructor takes a reference to an object of the same class as an argument.

What happens when we do not make our own copy constructor?

When we don't provide implementation of copy constructor (and assignment operator) and tries to initialize object with already initialized object of same class then copy constructor gets called and copies members of class one by one in target object.

What is copy constructor when it is used implicitly for what purpose?

Copy Constructor is called when an object is either passed by value, returned by value, or explicitly copied. If there is no copy constructor, c++ creates a default copy constructor which makes a shallow copy. If the object has no pointers to dynamically allocated memory then shallow copy will do.


2 Answers

After reading through the tutorial I was a little confused myself by the wording. But I believe it's as simple as this: the tutorial was explaining why the allocator's template header shows

allocator(const allocator&) throw();

and

template <class U> allocator(const allocator<U>&) throw();

even though the copy constructor is fairly useless for an allocator. And the answer was that the specification of an allocator does not allow the constructor to throw exceptions. Therefore the copy constructor public interface defines copy constructors with an exception specification of throw() (does not throw any exceptions) to prevent someone deriving their own allocator with copy constructors which might throw an exception.

See this link for a good description of what an exception specification is if that's what was throwing you. (No pun intended. Really.)

So, they didn't mean that when creating an allocator, you have to provide a copy constructor. They just were pointing out that the specification specifically prohibits you from defining one that throws any exceptions. `

like image 63
shelleybutterfly Avatar answered Sep 28 '22 03:09

shelleybutterfly


The allocator requires a copy constructor because containers have a copy constructor and will need to copy their allocator in the process.

like image 38
Peter Alexander Avatar answered Sep 28 '22 03:09

Peter Alexander