Afficher un message
Vieux 06/02/2008, 19h21   #4
Andrey Tarasevich
Aucun Avatar
 
Messages: n/a
Hébergeur:
Par défaut Re: Rule of three example and some questions

Joe Greer wrote:
>> My questions are on the two starred lines,
>>
>> + If I do not use a default constructor I am getting a compile time
>> error

>
> std::vector initializes using the default constructor. In this case, it apparently
> creates one default initialized object and copies it 5 times to initialize all 5
> cells of the vector.
> ...


Well, strictly speaking 'std::vector' doesn't use the element's default
constructor anywhere internally. The element type is not required to
have the default constructor at all. The only places when the element's
default constructors might appear is the default arguments for some
member function of 'std::vector'. Yet, once again, 'std::vector' never
relies on these default arguments internally.

This means that it's always up to the user whether to use these default
arguments (and, consequently, the default constructor of the element
type) or not. In OP's case the default argument is used in the
initialization of 'std::vector<Exmpl> vectorExmpl(5)', which is really
just a shorthand for 'std::vector vectorExmpl(5, Exmpl(),
std::allocator<Exmpl>())', taking into account the default arguments.

So, it is not exactly correct to say that "std::vector initializes using
the default constructor". 'std::vector' always initializes its elements
by using the copy constructor. It is really the user who's [implicitly]
causing the default initialization for the filler element in this case.

--
Best regards,
Andrey Tarasevich
  Réponse avec citation
 
Page generated in 0,05447 seconds with 9 queries