473,396 Members | 1,784 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,396 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 2922
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: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
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...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
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...
0
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,...

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.