I'm writing a class which has, as members, dynamically allocated
valarrays. I'd like to overload the "=" operator so that, when
operating on two objects of my class, the valarray values of the rhs
will be assigned to the valarray values of the lhs.
Well, in doing so I have discovered something I don't understand about
this operator; it destroys my operands upon return. I've written the
following demo, simplified to use ints instead of valarrays:
#include <iostream>
using namespace std ;
class Foo
{
private:
char me ;
int* num ;
public:
Foo(char me_, int num_) //constructor
{
me = me_ ;
num = new int ;
*num = num_;
}
int GetNum() const // getter
{
return *num ;
}
Foo operator=(const Foo rhs)
{
*num = rhs.GetNum() ;
return *this ;
}
void print()
{
cout << me << " = " << *num << endl ;
}
~Foo()
{
cout << "Destroying " << me << endl ;
delete num ;
}
};
int main ()
{
Foo a( 'a', 2);
Foo b( 'b', 3);
cout << "Before operating..." << endl ;
a.print();
b.print();
a=b;
cout << "After operating..." << endl ;
a.print();
b.print();
cout << "All done!!" << endl ;
return 0;
}
Here is the output:
Before operating...
a = 2
b = 3
Destroying a
Destroying b
After operating...
a = 13691
b = 3
All done!!
Destroying b
*** malloc[683]: error for object 0x300470: Double free
Destroying a
*** malloc[683]: Deallocation of a pointer not malloced: 0x300460; This
could be........
Why does my overloaded operator= destroy its operands when it returns?
It doesn't even seem to care that I've declared the rhs as const!
Jerry Krinock
San Jose, CA USA 6 1407
* Jerry Krinock: Foo operator=(const Foo rhs) { *num = rhs.GetNum() ; return *this ; }
Are you sure you want to return a copy instead of a reference?
Btw., it would be a Good Idea to support copying.
In other words, (also) add a copy constructor.
--
A: Because it messes up the order in which people normally read text.
Q: Why is it such a bad thing?
A: Top-posting.
Q: What is the most annoying thing on usenet and in e-mail?
Jerry Krinock wrote: I'm writing a class which has, as members, dynamically allocated valarrays. I'd like to overload the "=" operator so that, when operating on two objects of my class, the valarray values of the rhs will be assigned to the valarray values of the lhs.
Well, in doing so I have discovered something I don't understand about this operator; it destroys my operands upon return. I've written the following demo, simplified to use ints instead of valarrays:
#include <iostream> using namespace std ;
class Foo { private: char me ; int* num ;
public: Foo(char me_, int num_) //constructor { me = me_ ; num = new int ; *num = num_; }
int GetNum() const // getter { return *num ; }
Foo operator=(const Foo rhs)
Foo operator=(const Foo& rhs) { *num = rhs.GetNum() ; return *this ; }
void print() { cout << me << " = " << *num << endl ; }
~Foo() { cout << "Destroying " << me << endl ; delete num ; } };
int main () { Foo a( 'a', 2); Foo b( 'b', 3);
cout << "Before operating..." << endl ; a.print(); b.print();
a=b;
cout << "After operating..." << endl ; a.print(); b.print();
cout << "All done!!" << endl ; return 0;
}
Here is the output:
Before operating... a = 2 b = 3 Destroying a Destroying b After operating... a = 13691 b = 3 All done!! Destroying b *** malloc[683]: error for object 0x300470: Double free Destroying a *** malloc[683]: Deallocation of a pointer not malloced: 0x300460; This could be........
Why does my overloaded operator= destroy its operands when it returns? It doesn't even seem to care that I've declared the rhs as const!
What's being destroyed is the local copy -- taking the memory allocated
to its pointer-to-int with it when its dtor runs.
HTH,
--ag
--
Artie Gold -- Austin, Texas http://it-matters.blogspot.com (new post 12/5) http://www.cafepress.com/goldsays
Thanks, Artie and Alf. I think I get most of it now. Since my
operator calls by value, a copy of the rhs is created. Furthermore,
when an object is returned by a function, it returns a temporary object
which is automatically created. Thus, both operands are copied when my
operator= is invoked. Since I did not have a copy constructor, these
were shallow copies. When I simply added a copy constructor,
everything worked as desired.
But, Alf, I think I am still returning a copy. How would I fix it to
return a reference, as you suggested?
Revised code and output follows:
Jerry
class Foo
{
private:
int* num ;
public:
char me ;
Foo(char me_, int num_)
{
me = me_ ;
num = new int ;
*num = num_;
}
Foo(const Foo &rhs) // copy constructor
{
me = rhs.me ;
num = new int ;
*num = rhs.GetNum() ;
cout << "Done copy construction of " << me << endl ;
}
int GetNum() const
{
return *num ;
}
Foo operator=(const Foo rhs)
{
*num = rhs.GetNum() ;
return *this ;
}
void print()
{
cout << me << " = " << *num << endl;
}
~Foo()
{
cout << "Destroying " << me << endl ;
delete num ;
}
};
int main ()
{
Foo a( 'a', 2);
Foo b( 'b', 3);
cout << "Before operating..." << endl ;
a.print();
b.print();
a=b;
cout << "After operating..." << endl ;
a.print();
b.print();
cout << "All done!!" << endl ;
return 0;
}
*** OUTPUT ***
Before operating...
a = 2
b = 3
Done copy construction of b
Done copy construction of a
Destroying a
Destroying b
After operating...
a = 3
b = 3
All done!!
Destroying b
Destroying a al***@start.no (Alf P. Steinbach) wrote in news:4215200b.3 9221062
@news.individua l.net: * Jerry Krinock: Foo operator=(const Foo rhs) { *num = rhs.GetNum() ; return *this ; }
Are you sure you want to return a copy instead of a reference?
Btw., it would be a Good Idea to support copying.
In other words, (also) add a copy constructor.
In addition, it's taking Foo in by value as well... that should probably
also be by reference.
* Jerry Krinock: How would I fix it to return a reference, as you suggested?
Foo operator=(const Foo rhs) { *num = rhs.GetNum() ; return *this ; }
Foo& operator=( Foo const& rhs )
{
*num = rhs.GetNum();
return *this;
}
--
A: Because it messes up the order in which people normally read text.
Q: Why is it such a bad thing?
A: Top-posting.
Q: What is the most annoying thing on usenet and in e-mail?
Ah, of course!!! Since an operator is in fact a function, I can use the
reference parameters syntax! And when I call by reference, I see that
the copy constructor is not called, so my program will run faster,
although I shall keep the copy constructor for other purposes.
Thank you all very much for teaching this old electrical engineer such
cool new tricks.
Jerry This thread has been closed and replies have been disabled. Please start a new discussion. Similar topics |
by: Roy Yao |
last post by:
Does it mean "(sizeof(int))* (p)" or "sizeof( (int)(*p) )" ?
According to my analysis, operator sizeof, (type) and * have the same
precedence, and they combine from right to left. Then this expression should
equal to "sizeof( (int)(*p) )", but the compiler does NOT think so. Why?
Can anyone help me? Thanks.
Best regards.
Roy
|
by: August1 |
last post by:
I've written an interface and implementation file along with a client
source file that allows the use of an overloaded subtraction operator.
However, when
using the program, I'm running into a memory problem that I'm not
readily seeing that lies within the overloaded operator - I think
pertaining to the temporary class object that is created and used to
return a value of the operands and the pointer variable of the class.
Could someone...
|
by: CoolPint |
last post by:
After upgrading to gcc 3.4.2 from gcc 3.2.3, I got compiler errors
that I could not figure out. After reading other postings, I learned
that my coding was not compliant to the standard in the first place
and I did fix many of them, especially with the proper use of the
keyword "typename".
But I have one problem I have no idea how to fix. I created below a
simpler coding which demonstrates my problem:
The coding below used to compile...
|
by: Christopher Benson-Manica |
last post by:
Of course one can get the effect with appropriate use of existing
operators, but a ^^ operator would make for nice symmetry (as well as
useful to me in something I'm working on). Am I the only one who
would find it useful?
--
Christopher Benson-Manica | I *should* know what I'm talking about - if I
ataru(at)cyberspace.org | don't, I need to know. Flames welcome.
|
by: Shawn Odekirk |
last post by:
Some code I have inherited contains a macro like the following:
#define setState(state, newstate) \
(state >= newstate) ? \
(fprintf(stderr, "Illegal state\n"), TRUE) : \
(state = newstate, FALSE)
This macro is called like this:
setState(state, ST_Used);
| |
by: B. Williams |
last post by:
I have an assignment for school to Overload the operators << and >and I
have written the code, but I have a problem with the insertion string
function. I can't get it to recognize the second of number that are input so
it selects the values from the default constructor. Can someone assist me
with the insertion function. The code is below.
// Definition of class Complex
#ifndef COMPLEX1_H
|
by: rohits123 |
last post by:
I have an overload delete operator as below
//////////////////////////////////
void operator delete(void* mem,int head_type) {
mmHead local_Head = CPRMemory::GetMemoryHead(head_type);
mmFree(&local_Head,(char *)mem);
CPRMemory::SetMemoryHeadAs(local_Head,head_type);
}
/////////////////////
void* operator new(size_t sz, int head_Type) {
|
by: Peter Lee |
last post by:
what's the correct behaver about the following code ? ( C++
standard )
I got a very strange result....
class MyClass
{
public:
MyClass(const char* p)
{
printf("ctor p=%s\n", p);
|
by: sam_cit |
last post by:
Hi Everyone,
I was just wondering, about the overloaded assignment operator for
user defined objects. It is used to make sure that the following works
properly,
obj1 = obj;
so the overloaded operator function performs the necessary copy of
obj's member in to obj1. Can't the same be done using copy
|
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: 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: 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...
|
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: adsilva |
last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
|
by: muto222 |
last post by:
How can i add a mobile payment intergratation into php mysql website.
| |
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...
| |