473,837 Members | 1,758 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

about copy constructor and destructor

Hello experts!

I have this piece of code. No user defined copy constructor exist.
AccountForStude nt create(long number)
{
AccountForStude nt local(number, 0.0);
return local;
}
int main()
{
AccountForStude nt 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.

Now to my question: temp and local will share the same Student object
because we have a shallow copy.
When the destructor for temp executes the Student object is deallocated and
therefore you now cannot access the Student object through the variable
global.
The strange thing here is first the destuctor for object local must also
have been called.
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?.

Here is the class definition for AccountForStude nt
class AccountForStude nt
{
public:
AccountForStude nt(long number, double balance);
~AccountForStud ent();
long getNumber() const;
. . .
private:
Student* stud_;
double balance_;
};

Many thanks

//Tony

Aug 11 '05 #1
3 2111
Tony Johansson wrote:
I have this piece of code. No user defined copy constructor exist.
AccountForStude nt create(long number)
{
AccountForStude nt local(number, 0.0);
return local;
}
int main()
{
AccountForStude nt 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.
Actually, I'd move 5 between 2 and 3.
Now to my question: temp and local will share the same Student object
because we have a shallow copy.
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?
When the destructor for temp executes the Student object is deallocated and
therefore you now cannot access the Student object through the variable
global.
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.
The strange thing here is first the destuctor for object local must also
have been called.
Ah, yes, that's what I just described above.
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?.
It causes _undefined_beha viour_. 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.
Here is the class definition for AccountForStude nt
class AccountForStude nt
{
public:
AccountForStude nt(long number, double balance);
~AccountForStud ent();
long getNumber() const;
. . .
private:
Student* stud_;
double balance_;
};


V
Aug 11 '05 #2
Tony Johansson wrote:
I have this piece of code. No user defined copy constructor exist.
In effect, the C++ compiler supplies a default copy constructor.
AccountForStude nt create(long number) {
AccountForStude nt local(number, 0.0);
return local;
}
Why not

AccountForStude nt create(long number) {
return local(number, 0.0);
}
int main(int argc, char* argv[]) {
AccountForStude nt global;
global = create(300);

return 0;
}
Why not

int main(int argc, char* argv[]) {
AccountForStude nt global = create(300);
return 0;
}
Here is what happen according to a book:
Which book?
1. Program execution enters the body of create()
and the variable local in initialized by calling the [explicit] constructor.
No! A good optimizing compiler
will recognize local as an alias for the return value
and initialize it directly -- no local object is created or destroyed.
This is called the Named Return Value Optimization (NRVO).
2. A temporary variable 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.
No!
The compiler emits code to pass a reference to the temporary variable
to function create as a [hidden] argument
which represents the return value.
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.
This is unnecessary if you use create(long) to initialize global
as shown in my example above.
5. create() terminates.
No!
create(long) terminates *before* the assignment.
The temporary variable is created in the scope of the calling program
so it must be destroyed in the scope of the calling program --
after create returns.
Now to my question: temp and local will share the same Student object
because we have a shallow copy.
Meaning, I suppose, that you don't copy the Student object *stud_.
When the destructor for temp executes,
the Student object is deallocated and, therefore,
you now cannot access the Student object through the variable global.
That's stupid.
You need to define a copy constructor and assignment operator
which do a *deep* copy
if you are going to define a "deep" destructor.

The strange thing here is [that]
first the destuctor for object local must also have been called.
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?.
You *might* be right.
Here is the class definition for AccountForStude nt:

class AccountForStude nt {
public:
AccountForStude nt(long number, double balance);
~AccountForStud ent(void);
long getNumber(void) const;
// . . .
private:
Student* stud_;
double balance_;
};

Aug 11 '05 #3

"E. Robert Tisdale" <E.************ **@jpl.nasa.gov > wrote in message
news:dd******** **@nntp1.jpl.na sa.gov...
Tony Johansson wrote:
AccountForStude nt create(long number) {
AccountForStude nt local(number, 0.0);
return local;
}


Why not

AccountForStude nt create(long number) {
return local(number, 0.0);
}

I think you mean
return AccountForStude nt (number, 0.0);

/dan
Aug 12 '05 #4

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

4
1435
by: Apricot | last post by:
#include <iostream> #include <string> #include <map> using namespace std ; class tst { public : tst() { cout << "tst::constructor" << endl ; } tst(const tst & that) { cout << "tst::copy constructor" << endl ; }
4
1817
by: away | last post by:
1. When a class defined with a member of pointer type, it's necessary to have a copy constructor and assignment operator. If don't pass objects of such class as value in a function and don't do assignment, should copy constructor and assignment operator be unnecessary? 2. If a base class have a pointer member, should its derived classes also need copy constructor and assignment operator, no matter if a derived class itself has a...
3
1929
by: Matt Bitten | last post by:
Hi, all. I have the same old problem about templates and copy constructors. I know this has been addressed hundreds of times, but despite perusing many old postings, and The Standard as well, I'm still feeling confused. Suppose I have a class template: template <typename T> class Foo {
11
1562
by: cfchou | last post by:
hi, all, i'm reading ch.20 -smart pointers- of . and i'm tring the trule.hpp test. but there's something different than i expect, and i found that's about temp object. so i simplified the question into the following code: ===code starts=== #include <iostream> using namespace std;
3
1519
by: lhr_cool_guy | last post by:
The following code is compiling correctly on Visual Studio .NET 2003 but crashes. The problem is that the copy constructor is not being called when it should be. Am I doing something wrong or is the compiler at fault? I don't have any other compilers on which I could test this :( If it IS a problem in the compiler, are there any workarounds? template< class T > class C {
3
1765
by: ennio | last post by:
Hi, i have a doubt i can't solve right now. Your help will be appreciated. I am studying constructors/copy constructors/destructors. I created this a little class (see below). If i comment the destructor (~Mine), i get the following lines as i execute main: "Constructor Copy Constructor" , as i expected (in the main function i initialize a variable).
3
1779
by: sarathy | last post by:
Hi all, I have doubt regarding how objects are passed in C++. The primary problem of passing by value in C++, is that the destructor of the object passed will be called twice, thus creating possible damage to the object passed. If that is the case, why isnt the following program producing the unexpected o/p. I expect the program to print In B::printValues : 22 33 instead of
7
2167
by: pallav | last post by:
I'm having some trouble with my copy constructor. I've tried using gdb to find the bug, but it seg faults in the destructor. I'm not able to see what I'm doing wrong. Since I'm using pointers, I need deep copy and I believe I'm doing that in my constructors. Can someone help me see what I'm missing out? Here is my code. typedef boost::shared_ptr<FactorFactorPtr; enum FactorTypeT
10
2436
by: JosephLee | last post by:
In Inside C++ object Model, Lippman said there are four cases in which compile will sythesize a default constructor to initialize the member variables if the constructor is absent: 1. there is a virtual function; 2. virtual inheritance; 3.base class with explicit default constructor;
0
10580
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
10277
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
9413
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7817
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
7007
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5674
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5853
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4479
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
3
3126
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.