473,326 Members | 2,113 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,326 software developers and data experts.

Checking assignment operators with *this pointer

Hey,

I know we use the pointer this to obtain a class object or class
member data. I don't follow the reason for example this code. I'am
quite confused

assingment operator
const B &operator=(const B& x){

if (&x != this)
a = x.a;

else
return *this;
}
This is how i see this code. its compares the reference of x to the
adress of the this pointer??

In a line like this, i don't follow the steps the compiler takes.
b1 = b2;

Code below

---------------------------------------------------------------------
#include <iostream>
using namespace std;
class A
{
int n ;

public:
A():n(0)
{
}
A(int x):n(x)
{
n = x;
}
A(A &c):n(){

n = c.n;
}
void print()
{ cout << n<<"\n\n";
}
A(const A& objectCopy){
n = objectCopy.n; // copy constructor
}
const A &operator=(const A x){
n = x.n; // Operator

}
void good(){
cout<< this->n<<"";
}

};
class B
{
A * a;

int v;

public:
B(A & x)
{
a = new A(x);
}
void print ()
{
a->print();
}
B(const B& copy){ // Class B copy constructor
a = copy.a;

}
const B &operator=(const B& x){
if (&x != this)
a = x.a;
else
return *this;

// return *this;
//delete a;
}
B::~B(){
delete a;
}

};
//-------------------------------------------------------------------------*--

int main()
{

{

A a1(5);
A a2(7);
B b1(a2);
b1.print();
B b2(a1);
b1 = b2;
b1.print();
a1.good();

}

cout << endl;
int trick;
cin >trick;
return 0;
}
//-------------------------------------------------------------------------*-------
thnak you

Apr 25 '07 #1
3 2910
john wrote:
Hey,

I know we use the pointer this to obtain a class object or class
member data. I don't follow the reason for example this code. I'am
quite confused

assingment operator
const B &operator=(const B& x){

if (&x != this)
a = x.a;

else
'else' should be dropped.
return *this;
}
This is how i see this code. its compares the reference of x to the
adress of the this pointer??
No, it compares the _address_ of the 'x' object to the 'this' pointer.
>
In a line like this, i don't follow the steps the compiler takes.
b1 = b2;
Have you tried looking at assembly or stepping through the code in
a debugger? It helps.
>
Code below
[..snip..]
V
--
Please remove capital 'A's when replying by e-mail
I do not respond to top-posted replies, please don't ask
Apr 25 '07 #2
"john" <wo*********@gmail.comwrote in message
news:11*********************@o40g2000prh.googlegro ups.com...
Hey,

I know we use the pointer this to obtain a class object or class
member data. I don't follow the reason for example this code. I'am
quite confused

assingment operator
const B &operator=(const B& x){

if (&x != this)
a = x.a;

else
return *this;
}
This is how i see this code. its compares the reference of x to the
adress of the this pointer??

In a line like this, i don't follow the steps the compiler takes.
b1 = b2;

Code below
[snip code]

It's to check for self assignment. Consider.

myclass A;

A = A;

This could also occur using pointers. You get an instance of myclass using
new and through the course of the program wind up trying to assign the
instance to itself.

In a trivial program where a is a built in type it's not a problem. But
there are casses where you may be storing things on the stack. Consider the
case where a is actually a pointer. An assignment operator would be tempted
to do something like this:

// consider a to be an int pointer. consider size to be a variable with
it's size.
const B &operator=(const B& x)
{
delete a;
a = new int[x.size]
for ( size_t i = ; i < size; ++i )
a[i] = x.a[i];

return *this;
}

Seems all well and good. We delete our current array, create a new one with
the proper size, then copy the contents. But what happens when self
assignment occurs? When x is actually this. As soon as we delete a we just
screwed up. We no longer have the memory to copy from, since we just
released it. That's where we check to make sure we aren't doing self
assignment.

const B &operator=(const B& x)
{
if ( &x != this )
{
delete a;
a = new int[x.size]
for ( size_t i = ; i < size; ++i )
a[i] = x.a[i];
}

return *this;
}

this is a pointer to our current instance. It compares it with the address
of the instance to copy from. If they are the same, then self assignment is
occuring. We don't have to copy or assign anything, since we'd just be
copying from ourselves.
Apr 25 '07 #3
On Apr 25, 5:38 am, "Jim Langston" <tazmas...@rocketmail.comwrote:
"john" <worldsou...@gmail.comwrote in message
news:11*********************@o40g2000prh.googlegro ups.com...
I know we use the pointer this to obtain a class object or class
member data. I don't follow the reason for example this code. I'am
quite confused
assingment operator
const B &operator=(const B& x){
if (&x != this)
a = x.a;
else
return *this;
}
There is no reason for such code. It is completely incorrect.
This is how i see this code. its compares the reference of x to the
adress of the this pointer??
In a line like this, i don't follow the steps the compiler takes.
b1 = b2;
Code below
[snip code]
It's to check for self assignment.
Which if necessary, is generally an indication of an error
elsewhere in the operator.
Consider.
myclass A;
A = A;
This could also occur using pointers. You get an instance of myclass using
new and through the course of the program wind up trying to assign the
instance to itself.
Not just with new. In fact, most of the time, self assignment
occurs when working with arrays of the objects.
In a trivial program where a is a built in type it's not a problem.
If it's a problem, it's a problem with the assignment operator
of a.
But there are casses where you may be storing things on the
stack. Consider the case where a is actually a pointer. An
assignment operator would be tempted to do something like
this:
// consider a to be an int pointer. consider size to be a variable with
it's size.
const B &operator=(const B& x)
{
delete a;
a = new int[x.size]
for ( size_t i = ; i < size; ++i )
a[i] = x.a[i];
return *this;
}
Seems all well and good.
No it doesn't. What happens if the new expression fails?
We delete our current array, create a new one with
the proper size, then copy the contents. But what happens when self
assignment occurs? When x is actually this. As soon as we delete a we just
screwed up. We no longer have the memory to copy from, since we just
released it. That's where we check to make sure we aren't doing self
assignment.
But the code is broken even without self-assignment. Checking
for self assignment doesn't fix this.
const B &operator=(const B& x)
{
if ( &x != this )
{
delete a;
a = new int[x.size]
for ( size_t i = ; i < size; ++i )
a[i] = x.a[i];
}
return *this;
}
Which still has the same problem as the original. If the new
expression fails, you end up with an object that cannot be
destructed.
this is a pointer to our current instance. It compares it with the address
of the instance to copy from. If they are the same, then self assignment is
occuring. We don't have to copy or assign anything, since we'd just be
copying from ourselves.
The correct way of handling this is to build up the new object
first, before the delete:

B&
B::operator=(
B const& other )
{
X* newA = new int[ other.size ] ;
for ( size_t i = 0 ; i < other.size ; ++ i ) {
newA[ i ] = other.a[ i ] ;
}
delete a ;
size = other.size ;
a = newA ;
return *this ;
}

Alternatively, you can use the swap idiom:

void
B::swap( B& other ) throw()
{
std::swap( size, other.size() ) ;
std::swap( a, other.a ) ;
}

B&
B::operator=(
B const& other )
{
B tmp( other ) ;
swap( tmp ) ;
return *this ;
}

This has the advantage of being simple to understand. It's
widely used, and can be considered idiomatic C++. It's
supported by the standard library (e.g. all of the standard
containers have no-throw versions of swap).

You'll notice, of course, that no check for self assignment is
necessary.

--
James Kanze (GABI Software) email:ja*********@gmail.com
Conseils en informatique orientée objet/
Beratung in objektorientierter Datenverarbeitung
9 place Sémard, 78210 St.-Cyr-l'École, France, +33 (0)1 30 23 00 34

Apr 26 '07 #4

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

Similar topics

8
by: Nitin Bhardwaj | last post by:
Thanx in advance for the response... I wanna enquire ( as it is asked many a times in Interviews that i face as an Engg PostGraduate ) about the overloading capability of the C++ Language. ...
9
by: Rick N. Backer | last post by:
I have an abstract base class that has char* members. Is an assignment operator necessary for this abstract base class? Why or why not? Thanks in advance. Ken Wilson Amer. Dlx. Tele,...
14
by: sathya_me | last post by:
Dear clc, I have a variable void *a; Since variable "a" can be assigned (point to) any type and also any type can be assigned to "a" (i.e means "a" = any typed variable; any typed variable =...
11
by: anongroupaccount | last post by:
What measures should be taken to avoid this sort of thing? class Base { }; class Derived1 : public Base { private: int i, j, k;
3
by: Abubakar | last post by:
Hi, lets say I have a class called "hashstring". I want to be able to write the following code: hashstring hs ( "hello world" ); char * somecharptr; somecharptr = hs; // here the somecharptr...
1
by: Raghuram N K | last post by:
Hi, Following program compiles and executes successfully in windows with DevCPP compiler. When I compile the same in Linux with 'g++323' compiler I get following assignment error: cannot...
5
by: raylopez99 | last post by:
I need an example of a managed overloaded assignment operator for a reference class, so I can equate two classes A1 and A2, say called ARefClass, in this manner: A1=A2;. For some strange reason...
1
by: john | last post by:
Hey, I'am confused on the principles on checking a assingment operators using This pointer. I understand using *this to access data member in a class. const B &operator=(const B& x){ if...
8
by: aarklon | last post by:
Hi all, see:- http://linuxgazette.net/issue51/pramode.html
0
by: DolphinDB | last post by:
Tired of spending countless mintues downsampling your data? Look no further! In this article, you’ll learn how to efficiently downsample 6.48 billion high-frequency records to 61 million...
0
by: ryjfgjl | last post by:
ExcelToDatabase: batch import excel into database automatically...
0
by: Vimpel783 | last post by:
Hello! Guys, I found this code on the Internet, but I need to modify it a little. It works well, the problem is this: Data is sent from only one cell, in this case B5, but it is necessary that data...
0
by: jfyes | last post by:
As a hardware engineer, after seeing that CEIWEI recently released a new tool for Modbus RTU Over TCP/UDP filtering and monitoring, I actively went to its official website to take a look. It turned...
1
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
1
by: Defcon1945 | last post by:
I'm trying to learn Python using Pycharm but import shutil doesn't work
0
by: af34tf | last post by:
Hi Guys, I have a domain whose name is BytesLimited.com, and I want to sell it. Does anyone know about platforms that allow me to list my domain in auction for free. Thank you
0
by: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 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 former...

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.