473,796 Members | 2,464 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

nonmember function swap used in assignment


So I'm reading the C++ coding standards(Shutt er & Andrei), more
specifically item 56. There's a statement:
"Prefer to provide a nonmember swap function in the same namespace as
your type when objects of your type have a way to exchange their values
more efficiently than via brute-force assignment, such as if they have
their own swap or equivalent function. Additionally, consider
specializing std::swap for your own template types:"

namespace std {
template <> void swap(MyType& lhs, MyType& rhs) {
lhs.swap(rhs);
}
}
-------- end shutter/andrei

So I'm trying to generate a case where to just that. Provide my own
'non member swap function'. So consider:

// test case
# include <iostream>
# include <string>
# include <algorith>

using namespace std;

class msg {
std::string msg_id;
size_t val;
public:
explicit msg(
std::string const& msg_id_,
int val_
)
: msg_id(msg_id_)
, val(val_) {}

msg& msg::operator=( const msg& m)
{
msg temp(m);
swap(temp);
return *this;
}

void swap(msg &rhs) {
msg_id.swap(rhs .msg_id);
std::swap(val, rhs.val);
}

};

namespace std {
template <> void swap(msg& lhs, msg& rhs) {
lhs.swap(rhs);
}
}

class my_class {
msg *my_msg;
public:
explicit my_class() {}
void do_a_special_th ing(msg& msg_)
{
//my_msg = msg_;
}
};

int main()
{
my_class m;
m.do_a_special_ thing(msg("hi there" , 5));
}
the function do_a_special_th ing should assing msg_ to my_msg utilizing
my 'non member swap function', but there's something amiss about my
approach here so always appreaciate the help.

// formerly [ma******@pegasu s.cc.ucf.edu]

Oct 2 '05 #1
2 1983

ma******@gmail. com wrote:
So I'm reading the C++ coding standards(Shutt er & Andrei)
Great book, just finished it.
# include <algorith>
Missing 'm' in 'algorithm'
class msg {
Syle note:
Consider writing this out ('message') or otherwise marking this as a
class type (capital first letter maybe?). Otherwise variable namimg is
going to be difficult/confusing.
std::string msg_id;
Style note 2:
You're using a trailing _ for function arguments (ex. val_). While
there's certainly no "right" way of variable namimg, the very book you
were reading suggests the trailing _ for private member variables (like
this msg_id) [Coding Standards, Item 0].
msg *my_msg;
This should read 'msg my_msg' (no pointer). Otherwise the assignment
below won't work.
public:
explicit my_class() {}
You made the my_msg constructor that takes two parameters explicit. So
in my_class's constructor, you'll have to initialize my_msg with two
arguments somehow.

If you change the my_msg to be a msg (instead of a msg*), this would
work:

explicit my_class() : my_msg( "undefined" , 0 ){}

You get the picture...
void do_a_special_th ing(msg& msg_)
{
//my_msg = msg_;
}
If my_msg is not a pointer, this will work.

You could also use the srd::swap directly here:

std::swap( my_msg, msg_ );
m.do_a_special_ thing(msg("hi there" , 5));
This doesn't work. Instead create the msg first, then call the func.:

msg hi( "hi there", 5 );
m.do_a_special_ thing( hi );
the function do_a_special_th ing should assing msg_ to my_msg utilizing
my 'non member swap function', but there's something amiss about my
approach here so always appreaciate the help.
It would help next time if you tried to compile your own code and refer
to the part of the code that you have problems with.

Hope this helps...

Cheers,
Andre
// formerly [ma******@pegasu s.cc.ucf.edu]


Oct 2 '05 #2
|| the very book you were reading suggests the
|| trailing _ for private member variables (like
|| this msg_id)

:)

Ok I'll try your suggestions... For test purposes I generally overlook
all sorts of stuff. In any event, thanks

Oct 2 '05 #3

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

Similar topics

3
3469
by: Andrew Koenig | last post by:
I am looking for the most effective way to exchange v and v, and expected to find something like v.swap(i, j) but it doesn't seem to exist. Is there anything better than v, v = v, v (which I don't like particularly because it evaluates each of v and v
13
2445
by: Erik Haugen | last post by:
From reading gotw#84 (http://www.gotw.ca/gotw/084.htm), I'm convinced that I should try to make functions nonfriend nonmembers when practical, but then I came across this: Bruce Eckel says about operator overloads in Thinking In C++ (2nd Ed - http://www.codeguru.com/cpp/tic/tic0129.shtml) "In general, if it doesn't make any difference, they should be members, to emphasize the association between the operator and its class." That seems...
12
2983
by: RA Scheltema | last post by:
Hi all, I have the following code: namespace A { inline void func(int) { ...; } inline void func(float) { ...; } inline void func(char) { ...; } }
12
1903
by: ypjofficial | last post by:
Hello All, I need to return a vector from a function.The vector is of int and it can contain as many as 1000 elements.Earlier I was doing //function definition vector<intretIntVector() { vector<intvecInt; /* //Populate the vector with int values.
28
2859
by: Jess | last post by:
Hello, It is said that if I implement a "swap" member function, then it should never throw any exception. However, if I implement "swap" non- member function, then the restriction doesn't apply. Can somebody tell me why? Thanks, Jess
13
3973
by: JD | last post by:
Hi, My associate has written a copy constructor for a class. Now I need to add an operator = to the class. Is there a way to do it without change her code (copy constructor) at all? Your help is much appreciated. JD
12
1827
by: raj s | last post by:
What is the advantage and disadvantage of using function declaration with exceptions specified. like foo()throws(char&)
21
1896
by: raylopez99 | last post by:
In the otherwise excellent book C# 3.0 in a Nutshell by Albahari et al. (3rd edition) (highly recommended--it's packed with information, and is a desktop reference book) the following statement is made: (p. 39: "The ref modifier is essential in implementing a swap method") This is untrue. The following program demonstrates it. See how method "func4Swap" does a swap of two int variables without using ref, but using a 'helper' class and...
0
9680
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
10455
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
10006
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 protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
6788
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
5441
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...
0
5573
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4116
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
3731
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2925
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.