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?
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.
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.
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.
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. `
The allocator requires a copy constructor because containers have a copy constructor and will need to copy their allocator in the process.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With