| re: about copy constructor and destructor
Tony Johansson wrote:[color=blue]
> I have this piece of code. No user defined copy constructor exist.
> AccountForStudent create(long number)
> {
> AccountForStudent local(number, 0.0);
> return local;
> }
> int main()
> {
> AccountForStudent global;
> global = create(300);
>
> return 0;
> }
>
> Here is what happen according to a book.:
> 1. Program execution enters the body of create(), and the variable local in
> initialized by calling the constructor.
> 2. A temporary variable, temp, created by the compiler, is initialized by
> calling the compiler generated copy constructor because no other is defined
> and using the value of the local variable.
> 3. An assignment operator is called, which assign the value of the temporary
> variable temp to global.
> 4.The destructor for the temporary variable temp is called.
> 5. create() terminates.[/color]
Actually, I'd move 5 between 2 and 3.
[color=blue]
> Now to my question: temp and local will share the same Student object
> because we have a shallow copy.[/color]
How is that? Is 'Student' object in the temporary and 'local' identified
by the pointer and created in the free store by the 'local's constructor?
[color=blue]
> When the destructor for temp executes the Student object is deallocated and
> therefore you now cannot access the Student object through the variable
> global.[/color]
Actually, this might happen even sooner. When 'local' is destroyed, the
pointer to it (I am assuming it's a pointer) in the temporary becomes
invalid, and while the value of that pointer is copied into 'global', the
validity of it has already been disrupted.
[color=blue]
> The strange thing here is first the destuctor for object local must also
> have been called.[/color]
Ah, yes, that's what I just described above.
[color=blue]
> When this was called and tries to deallocate the Student object that already
> has been deallocated by the temp object. This will as I think destroy the
> free heap list and cause a crash. Am I right?.[/color]
It causes _undefined_behaviour_. Whether that means "crash" or some kind
of destruction "the free heap", I don't know.
The trick here is that the compiler is allowed to employ NRVO (named
return value optimization), and forgo creation of a temporary and use the
'local' object instead. That means only one object will be destroyed
after 'create' function returns, not two.
[color=blue]
> Here is the class definition for AccountForStudent
> class AccountForStudent
> {
> public:
> AccountForStudent(long number, double balance);
> ~AccountForStudent();
> long getNumber() const;
> . . .
> private:
> Student* stud_;
> double balance_;
> };[/color]
V |