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 3 2108
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
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_; };
"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 This thread has been closed and replies have been disabled. Please start a new discussion. Similar topics |
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 ;
}
|
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...
|
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 {
|
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;
|
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
{
| |
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).
|
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
|
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
|
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;
|
by: marktang |
last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look !
Part I. Meaning of...
|
by: Hystou |
last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it.
First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
| |
by: Oralloy |
last post by:
Hello folks,
I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>".
The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed.
This is as boiled down as I can make it.
Here is my compilation command:
g++-12 -std=c++20 -Wnarrowing bit_field.cpp
Here is the code in...
|
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...
|
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...
|
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();...
|
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...
|
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
| |
by: muto222 |
last post by:
How can i add a mobile payment intergratation into php mysql website.
| |