473,666 Members | 2,634 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

question on the assignment operator


Consider:

# include <iostream>
# include <algorithm>
# include <vector>
# include <string>
using namespace std;

class msg {
std::string someStr;
public:
msg(const std::string& sStr)
: someStr(sStr) {}
msg( const msg& rhs )
: someStr(rhs.som eStr)
{}
void swap( msg& rhs ) {
std::swap( someStr, rhs.someStr );
}
msg& operator=( const msg& rhs) {
msg tmp (rhs);
swap(tmp);
return *this;
}
std::string get_some_str() const { return someStr; }
};

class Y {
typedef std::vector<msg > msgVec;
msgVec msg_vec;
public:
Y(){}
Y( const Y& rhs )
: msg_vec(rhs.msg _vec)
{}
void swap( Y& rhs ) {
std::swap( msg_vec, rhs.msg_vec );
}
Y& operator=( const Y& rhs) {
Y tmp (rhs);
swap(tmp);
return *this;
}
void add(msg& ms)
{ msg_vec.push_ba ck(ms); }

void print()
{
if (msg_vec.size() )
std::cout << msg_vec[0].get_some_str() << std::endl; // just for
test
}

};

class Controller {
typedef std::vector<Y> VEC_Y;
VEC_Y vectorOfYs;
public:

Controller() {}
Controller( const Controller& rhs )
: vectorOfYs(rhs. vectorOfYs)
{}

void swap( Controller& rhs ) {
std::swap( vectorOfYs, rhs.vectorOfYs );
}
Controller& operator=( const Controller& rhs) {
Controller tmp (rhs);
swap(tmp);
return *this;
}

void add_y(Y myY)
{ vectorOfYs.push _back(myY);}

void add_msg ( msg& ms )
{
if (vectorOfYs.siz e())
vectorOfYs[0].add(ms); // brute force for test.
}
void print() {
if (vectorOfYs.siz e())
vectorOfYs[0].print(); // just experimenting
}
};

int main()
{
Controller ctrl1;
ctrl1.add_y(Y() );
ctrl1.add_msg(m sg("test"));

Controller ctrl2;
ctrl2 = ctrl1;
ctrl2.print();
}
For assignment between two controller objects, the fact that the class
Controller contains a vector of Y's which in turn contains a vector of
msg's; implies that theres - perhaps a requirement for a copy
constructor in all _three_ classes. Correct?

Jan 21 '06 #1
17 2033
ma740988 wrote:
Consider:

# include <iostream>
# include <algorithm>
# include <vector>
# include <string>
using namespace std;

class msg {
std::string someStr;
public:
msg(const std::string& sStr)
: someStr(sStr) {}
msg( const msg& rhs )
: someStr(rhs.som eStr)
{}
void swap( msg& rhs ) {
std::swap( someStr, rhs.someStr );
}
msg& operator=( const msg& rhs) {
msg tmp (rhs);
swap(tmp);
return *this;
Really? No, REALLY? Why not simply

someStr = rhs.someStr;
return *this;

?
}
std::string get_some_str() const { return someStr; }
};

class Y {
typedef std::vector<msg > msgVec;
msgVec msg_vec;
public:
Y(){}
Y( const Y& rhs )
: msg_vec(rhs.msg _vec)
{}
void swap( Y& rhs ) {
std::swap( msg_vec, rhs.msg_vec );
}
Y& operator=( const Y& rhs) {
Y tmp (rhs);
swap(tmp);
Again... WHY? Just assign:

msg_vec = rhs.msg_vec;
return *this;
}
void add(msg& ms)
void add(msg const & ms) // a bit better
{ msg_vec.push_ba ck(ms); }

void print()
{
if (msg_vec.size() )
std::cout << msg_vec[0].get_some_str() << std::endl; // just for
test
}

};

class Controller {
typedef std::vector<Y> VEC_Y;
VEC_Y vectorOfYs;
public:

Controller() {}
Controller( const Controller& rhs )
: vectorOfYs(rhs. vectorOfYs)
{}

void swap( Controller& rhs ) {
std::swap( vectorOfYs, rhs.vectorOfYs );
}
Controller& operator=( const Controller& rhs) {
Controller tmp (rhs);
swap(tmp);
<sigh>...
return *this;
}

void add_y(Y myY)
void add_y(Y const & myY)
{ vectorOfYs.push _back(myY);}

void add_msg ( msg& ms )
{
if (vectorOfYs.siz e())
if (!vectorOfYs.em pty()) // better
vectorOfYs[0].add(ms); // brute force for test.
}
void print() {
if (vectorOfYs.siz e())
if (!vectorOfYs.em pty()) // better
vectorOfYs[0].print(); // just experimenting
}
};

int main()
{
Controller ctrl1;
ctrl1.add_y(Y() );
ctrl1.add_msg(m sg("test"));

Controller ctrl2;
ctrl2 = ctrl1;
ctrl2.print();
}
For assignment between two controller objects, the fact that the class
Controller contains a vector of Y's which in turn contains a vector of
msg's; implies that theres - perhaps a requirement for a copy
constructor in all _three_ classes. Correct?


No, not really. Since none of those objects require any special
processing during copy-construction, the compiler-generated one
is just right.

Besides, why are you doing all this nonsense in the assignment
operators? Simply assign the damn members and move on to more
important things...

V
Jan 21 '06 #2
"Victor Bazarov" <v.********@com Acast.net> wrote in message
news:a4******** *************** *******@comcast .com...
ma740988 wrote:
Consider:

# include <iostream>
# include <algorithm>
# include <vector>
# include <string>
using namespace std;

class msg {
std::string someStr;
public:
msg(const std::string& sStr)
: someStr(sStr) {}
msg( const msg& rhs )
: someStr(rhs.som eStr)
{}
void swap( msg& rhs ) {
std::swap( someStr, rhs.someStr );
}
msg& operator=( const msg& rhs) {
msg tmp (rhs);
swap(tmp);
return *this;
Really? No, REALLY? Why not simply

someStr = rhs.someStr;
return *this;


Even further, why define operator= at all? Defining operator= unnecessarily
opens the risk of forgetting to assign any members that may be added in the
future. Forgetting to assign the base classes is another problem that I've
lived in the past.

[...]
No, not really. Since none of those objects require any special
processing during copy-construction, the compiler-generated one
is just right.
Agreed... I wanted to add operator=; because it should get the same
treatment as the copy constructor here :)
Besides, why are you doing all this nonsense in the assignment
operators? Simply assign the damn members and move on to more
important things...


Now I am beginning to suspect that there may be something special about
operator=. You agree that the compiler generated operator= is just right,
right? :)

Ali

Jan 21 '06 #3
Victor Bazarov wrote:
[...]

Besides, why are you doing all this nonsense in the assignment
operators? Simply assign the damn members and move on to more
important things...


To quote Sutter and Alexandrescu:
"It is often beneficient to use the swap function in the
assignment operator. The below mentioned implementation gives
strong reliability, although at the price of constructing an
extra object. If speed matters it should not be used"

T& T::operator=(co nst T& other) {
T temp(other);
swap(temp);
return *this;
}

So, if I understand correctly it means that if you make
the swap operation and the copy ctor unfailible (they don't
throw) that makes your assignment operator unfailible too.

That said, I think calling it "nonsense" is rather
strong worded.

Someone correct me if I'm wrong -- I only read the book
last week :)

cheers,
- J.
Jan 21 '06 #4
"Jacek Dziedzic" <jacek@no_spam. tygrys.no_spam. net> wrote in message
news:72******** *************** ***@news.chello .pl...
Victor Bazarov wrote:
[...]

Besides, why are you doing all this nonsense in the assignment
operators? Simply assign the damn members and move on to more
important things...
To quote Sutter and Alexandrescu:
"It is often beneficient to use the swap function in the
assignment operator. The below mentioned implementation gives
strong reliability, although at the price of constructing an
extra object. If speed matters it should not be used"

T& T::operator=(co nst T& other) {
T temp(other);
swap(temp);
return *this;
}


Though uncommon but even better implementation is:

T& T::operator=(T temp) // <-- note the copy
{
swap(temp);
return *this;
}

That version gives the compiler more help in optimizations.
So, if I understand correctly it means that if you make
the swap operation and the copy ctor unfailible (they don't
throw) that makes your assignment operator unfailible too.


No, only the swap needs to be non-throwing, and better be fast too (usually
is). Copy constructor can throw... The good thing is that, even if the copy
constructor throws, the state of the current object (the destination) is
unchanged. That is the power of doing the actual work on the side before
changing the state by non-throwing operations (swap in this case).

If additionally the copy constructor does not throw, then operator= does not
throw either.

Ali

Jan 21 '06 #5
Ali Çehreli wrote:
[...]
Though uncommon but even better implementation is:

T& T::operator=(T temp) // <-- note the copy
{
swap(temp);
return *this;
}

That version gives the compiler more help in optimizations.


Yep, that's what they mention on the next page :).
So, if I understand correctly it means that if you make
the swap operation and the copy ctor unfailible (they don't
throw) that makes your assignment operator unfailible too.



No, only the swap needs to be non-throwing, and better be fast too
(usually is). Copy constructor can throw... The good thing is that, even
if the copy constructor throws, the state of the current object (the
destination) is unchanged. That is the power of doing the actual work on
the side before changing the state by non-throwing operations (swap in
this case).

If additionally the copy constructor does not throw, then operator= does
not throw either.


Ah, thanks for the clarification!

cheers,
- J.
Jan 21 '06 #6
>
Again... WHY? Just assign:


That's the preferred approach if I recall correctly from - I believe -
Sutter 's text.

For assignment between two controller objects, the fact that the class
Controller contains a vector of Y's which in turn contains a vector of
msg's; implies that theres - perhaps a requirement for a copy
constructor in all _three_ classes. Correct?


No, not really. Since none of those objects require any special
processing during copy-construction, the compiler-generated one
is just right.

Actually, what I should have shown was an example were the msg class
dynamically allocated memory. In that case only the _msg_ class would
require an assignment operator?

Jan 21 '06 #7
ma740988 wrote:
Again... WHY? Just assign:


That's the preferred approach if I recall correctly from - I believe -
Sutter 's text.


Any justification for it that you actually understand? Following
somebody's "text" blindly has lead humanity to many a perils.
For assignment between two controller objects, the fact that the
class Controller contains a vector of Y's which in turn contains a
vector of msg's; implies that theres - perhaps a requirement for a
copy constructor in all _three_ classes. Correct?


No, not really. Since none of those objects require any special
processing during copy-construction, the compiler-generated one
is just right.

Actually, what I should have shown was an example were the msg class
dynamically allocated memory. In that case only the _msg_ class would
require an assignment operator?


See "the Rule of Three".

V
Jan 21 '06 #8
Any justification for it that you actually understand? Following
somebody's "text" blindly has lead humanity to many a perils. :)
See "the Rule of Three".

Right and that I know. I was trying to get a feel for the impact with
regards to class A, B and C. B has a vector of A and C has a vector of
B. I think I understand now, in that - for the scenario, I
highlighted in my initial post. if class msg dynamically allocated
memory, then class msg should provided the operator=, etc and that
would be all I need even though I'm assigning 'controller' objects.

Thanks

Jan 21 '06 #9
"Victor Bazarov" <v.********@com Acast.net> wrote in message
news:H7******** ************@co mcast.com...
ma740988 wrote:

See "the Rule of Three".


The rule of three can be understood, as I've done in the past, as "don't
define operator= if the class consists only of members that take care of
themselves."

With "taking care of themselves," I mean classes that define proper copy
constructors and assignment operators, which work correctly. Further, let's
take "working correctly" here as copying and assigning successfully.
Propagating exceptions should be fine too, if the object is left in a
consistent state. For example, std::string is such a class.

If one applies the guidelines as above, and believes that their class will
work correctly even if a member's operator= can throw, they might be dealing
with corrupt objects.

I think that the rule of three must go with an addition:

- Observe the rule of three (If any one of the three special functions needs
to be defined, chances are you will have to at least declare the other two)

- Additionally, if you want your objects be in a consistent state if a
member throws, always define operator=.

I've run a simple program to analyze what happens during the execution of
operator= when different operations throw or not and when operator= is
implicit or explicit.

A: a class without any members
B: a class that contains two std::strings and an A that is deliberately
defined between two strings

class B
{
string first_;
A a_;
string last_;

/* ... */
};

The legend for the table below:

completes: The operation completes successfully
throws: The operation is interrupted with an exception
implicit: The compiler generated operator= is used
explicit: operator= is defined by the user
new: The object gets the new state
old: The object is left in the old state
corrupt: The state of the object is corrupt

The results are:

A::A(A) A::operator=(A) B::operator=(B) | B's state
------------------------------------------------------|------------
completes completes implicit | new
throws completes implicit | new
completes throws implicit | corrupt
throws throws implicit | corrupt
completes completes explicit | new
throws completes explicit | old
completes throws explicit | new
throws throws explicit | old

What I digest from these results is:

1) If you leave operator= to the compiler (implicit) you may end up with a
corrupt object if operator= of a member throws

2) If you define operator= yourself (explicit) you may be left with the old
state

3) Otherwise you will get the new state

As a result, operator= is even more special that the other two, in that, it
prevents having an inconsistent object.

Here is the program I used to test these:

#include <iostream>
#include <string>

using namespace std;

// Comment-out or keep combinations of these macros to see the
// behavior for each case
// #define A_COPY_THROWS
// #define A_ASSIGNMENT_TH ROWS
// #define B_ASSIGNMENT_EX PLICIT

class A
{
public:

A()
{}

#if defined(A_COPY_ THROWS)
A(A const &)
{
throw 42;
}
#endif

#if defined(A_ASSIG NMENT_THROWS)
A & operator= (A const &)
{
throw 42;
}
#endif

void swap(A & other)
{}
};

class B
{
string first_;
A a_;
string last_;

friend ostream & operator<< (ostream &, B const &);

public:

explicit B(string const & value)
:
first_(value),
last_(value)
{}

bool operator== (B const & other) const
{
return ((first_ == other.first_)
&&
(last_ == other.last_));
}

#if defined(B_ASSIG NMENT_EXPLICIT)
B & operator= (B temp)
{
swap(temp);
return *this;
}
#endif

void swap(B & other)
{
first_.swap(oth er.first_);
a_.swap(other.a _);
last_.swap(othe r.last_);
}
};

ostream & operator<< (ostream & os, B const & b)
{
return os << b.first_ << ' ' << b.last_;
}

bool check_B_invaria nt(string const & label, B const & lhs, B const & rhs)
{
cout << label << ": ";

cout << "comparing " << lhs << " with " << rhs << '\n';

if ( ! (lhs == rhs))
{
cout << "NO ";
}

cout << "match\n";
}

int main()
{
B zero("0");
B b0("0");
B b1("1");

check_B_invaria nt("before", zero, b0);

try
{
b0 = b1;
check_B_invaria nt("completed" , b0, b1);
}
catch (...)
{
check_B_invaria nt("caught exception", b0, zero);
}
}
Ali
Jan 21 '06 #10

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

Similar topics

5
4828
by: CoolPint | last post by:
It seems to me that I cannot assign objects of a class which has a constant data member since the data member cannot be changed once the constructor calls are completed. Is this the way it is meant to be? Am I not suppose not to have any constant data member if I am going to have the assignment operator working for the class? Or am I missing something here and there is something I need to learn about? Clear, easy to understand...
11
1738
by: billnospam | last post by:
Is it possible to overload operators in vb.net? Is it possible to do programmer defined boxing on byvalue variables in vb.net?
10
2655
by: Christopher Benson-Manica | last post by:
Why can't I use a class destructor in a using declaration: using MyClass::~MyClass; ? -- 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.
9
1702
by: Matthew Polder | last post by:
Hi, When a class Apple is written and the assignment operator is not explicitly declared, the operator Apple& operator=(const Apple&) is created by the compiler. Is there any difference between this and const Apple& operator=(const Apple&)
56
4752
by: spibou | last post by:
In the statement "a *= expression" is expression assumed to be parenthesized ? For example if I write "a *= b+c" is this the same as "a = a * (b+c)" or "a = a * b+c" ?
5
2290
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 my C++.NET 2.0 textbook does not have one. I tried to build one using the format as taught in my regular C++ book, but I keep getting compiler errors. Some errors claim (contrary to my book) that you cannot use a static function, that you must...
2
614
by: sven.bauer | last post by:
Hi, I have a question following up the following slightly older posting: http://groups.google.de/group/comp.lang.c++/browse_thread/thread/40e52371e89806ae/52a3a6551f84d38b class Base { virtual Base& operator = (const Base &k) {} };
8
4395
by: JackC | last post by:
Hi, I am trying to get posix threads working from within an object, heres some code: int NConnection::TheadControl() { int thread_id; pthread_t new_connection; pthread_create(&new_connection, NULL, PriC, (void *)thread_id);
8
1309
by: hill.liu | last post by:
Hi, I stuck into this problem that I can't figure it out. Here is the class definition: class ctest { public: ctest(void) { cout << "ctest default constor" << endl; }; ctest(ctest& c) { cout <<"ctest copy constr" << endl; }; ctest(int a) { cout <<"ctest int constor" <<endl; };
7
3102
by: SchoolOfLife | last post by:
Hello, I'm studying C++ all by myself. I'm studying from C++ primer (4e) by S.B.Lippman, J. Lajoie and B.E.Moo. In chapter-1, there's a question whose answer I want to confirm. The question says: I think the answer to this question is that compound assignment operator is not a valid operation that is allowed on Sales_item objects. But I'm sure whether this is correct. Am I getting it right? If not, where am I wrong? Thank you very...
0
8440
marktang
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...
0
8352
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,...
0
8863
Oralloy
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...
0
8780
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...
1
6189
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
5661
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
4358
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
2765
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
2
1763
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.