473,569 Members | 2,870 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Weird return statement

Hello all,

I ve come across the following code fragment and I was wondering why is the
copy ctr called on return (rather than just returning the string statement
obj.

TIA

string PublishedProduc tsRepo :: CreateStatement () const {
string statement;

statement ="SELECT DISTINCT "
"* "
"FROM "
"map";
return string(statemen t); }
Mar 26 '06 #1
13 1857

jimjim skrev:
Hello all,

I ve come across the following code fragment and I was wondering why is the
copy ctr called on return (rather than just returning the string statement
obj.
The code below does not make much sense. I would have written it
simply:

string PublishedProduc tsRepo :: CreateStatement () const {
return "SELECT DISTINCT "
"* "
"FROM "
"map";
}

/Peter
TIA

string PublishedProduc tsRepo :: CreateStatement () const {
string statement;

statement ="SELECT DISTINCT "
"* "
"FROM "
"map";
return string(statemen t); }


Mar 26 '06 #2
* jimjim:

I ve come across the following code fragment and I was wondering why is the
copy ctr called on return (rather than just returning the string statement
obj.

string PublishedProduc tsRepo :: CreateStatement () const {
string statement;

statement ="SELECT DISTINCT "
"* "
"FROM "
"map";
return string(statemen t); }


Whether the copy constructor is called depends on your compiler and the
context of the CreateStatement call.

There is much that is unnecessary in the code, but it doesn't affect
copy constructor calls. What's important re copy constructor calls is
your compiler's optimizations.

A straightforward coding of this function is

std::string PublishedProduc tsRepo::CreateS tatement() const
{
return "SELECT DISTINCT * FROM map";
}

Note the qualification with "std::".

If this inline function definition is in a header file, which is likely,
the lack of such qualification in the original code indicates there is a
"using namespace std;" or "using std::string;" in the header file, which
in turn indicates an incompetent programmer. In other words, if those
reasonable assumptions hold, then this is not code to learn from.
Rather, it's then code from which you can learn how to /not/ do things.

For example:

* Don't ever place "using namespace std;" in a header file.

* Don't be clever when there is no need.

* Preferentially don't name a function "ComputeCos ine" when "cos" will
do: name value-producing functions for what they produce, not how.

--
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?
Mar 26 '06 #3
In article <D_************ ******@text.new s.blueyonder.co .uk>,
"jimjim" <ne*****@blueyo nder.co.uk> wrote:
I ve come across the following code fragment and I was wondering why is the
copy ctr called on return (rather than just returning the string statement
obj.

TIA

string PublishedProduc tsRepo :: CreateStatement () const {
string statement;

statement ="SELECT DISTINCT "
"* "
"FROM "
"map";
return string(statemen t); }


The person who wrote the code was probably worried because 'statement'
is a temporary and he wasn't sure if he was returning a temporary or
not. IE he didn't know the language very well.

Or maybe he was intentionally trying to obfuscate the code?
--
Magic depends on tradition and belief. It does not welcome observation,
nor does it profit by experiment. On the other hand, science is based
on experience; it is open to correction by observation and experiment.
Mar 26 '06 #4
Daniel T. wrote:
The person who wrote the code was probably worried because 'statement'
is a temporary and he wasn't sure if he was returning a temporary or
not. IE he didn't know the language very well.
You meant: ...probably worried because 'statement' is a local and he wasn't
sure if he was returning a reference to a local. So he returned a copy of a
temporary instead.
Or maybe he was intentionally trying to obfuscate the code?


The OP is advised to learn better C++ than that example before further
improvements. This will probably be tricky, because if the code has many
more examples like this then some of them might rely on undefined behavior.

--
Phlip
http://www.greencheese.org/ZeekLand <-- NOT a blog!!!
Mar 26 '06 #5
string PublishedProduc tsRepo :: CreateStatement () const {
string statement;

statement ="SELECT DISTINCT "
"* "
"FROM "
"map";
return string(statemen t); }


Looks like the coder isn't very proficient. Here's a few bad things:

1) The "statement" object is default constructed, and the an assignment
is performed. This is inefficent -- it should have just been a
construction:

string statement("bla bla");
2) There's no point in creating that nameless temporary in the "return"
statement. It could simply be:

return statement;
3) A proficient programmer would probably write:

string PublishedProduc tsRepo :: CreateStatement () const
{
return
"SELECT DISTINCT "
"* "
"FROM "
"map";
}
-Tomás
Mar 26 '06 #6
On Sun, 26 Mar 2006 18:20:50 +0200, "Alf P. Steinbach"
<al***@start.no > wrote:
Whether the copy constructor is called depends on your compiler and the
context of the CreateStatement call.


Whether the copy constructor is elided depends on your compiler, your
used compliler switches and the context of the CreateStatement call.
In general, it's not recommendable to make your code dependent on
language hacks like RVO.

Best regards,
Roland Pibinger
Mar 26 '06 #7
On Sun, 26 Mar 2006 18:27:14 GMT, "Tomás" <NU**@NULL.NULL > wrote:
3) A proficient programmer would probably write:

string PublishedProduc tsRepo :: CreateStatement () const
{
return
"SELECT DISTINCT "
"* "
"FROM "
"map";
}


That should be:

std::string PublishedProduc tsRepo :: CreateStatement () const
{
return std::string(
"SELECT DISTINCT "
"* "
"FROM "
"map");
}

--
Bob Hairgrove
No**********@Ho me.com
Mar 26 '06 #8
* Roland Pibinger:
On Sun, 26 Mar 2006 18:20:50 +0200, "Alf P. Steinbach"
<al***@start.no > wrote:
Whether the copy constructor is called depends on your compiler and the
context of the CreateStatement call.
Whether the copy constructor is elided depends on your compiler, your
used compliler switches and the context of the CreateStatement call.


Yes, I think you have understood that correctly.

In general, it's not recommendable to make your code dependent on
language hacks like RVO.


But not this.

On the contrary, it's absolutely not a good idea to resort to premature
optimization (Google for "premature optimization"): it wastes programmer
time and may end up making your program less efficient rather than more.

--
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?
Mar 26 '06 #9
Tomás wrote:
1) The "statement" object is default constructed, and the an assignment
is performed. This is inefficent -- it should have just been a
construction:

string statement("bla bla");
The compiler is required to directly call the constructor, even if = is
used.
2) There's no point in creating that nameless temporary in the "return"
statement. It could simply be:

return statement;
I do know that Return Value Optimization could make one of the strings
inside the function become an alias for the final string outside the
function. But I don't know how aggressive that rule is. Suppose the copy
constructor for std::string had a side effect that you could count. RVO will
make one of those side effects go away. (That's why it's a permitted
optimization and defined as "lossy"; so programmers will know better than to
depend on the number of side-effects from such constructors.)

Will RVO make all of this go away?

return string(string(s tring(string(st ring(string(sta tement))))));
3) A proficient programmer would probably write:

string PublishedProduc tsRepo :: CreateStatement () const
{
return
"SELECT DISTINCT "
"* "
"FROM "
"map";
}


And the next level of proficiency avoids this AntiPattern:

http://c2.com/cgi/wiki?PerniciousIngrownSql

--
Phlip
http://www.greencheese.org/ZeekLand <-- NOT a blog!!!
Mar 26 '06 #10

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

Similar topics

11
1444
by: HelLind | last post by:
Hello people, I am having a weird error and don't know what term to search in google. Sorry to bother. There is data in my field "M_BIO" When I run this code <%=rslist.Fields.Item("M_bio").Value%>, it displays the data, no problem.
2
6761
by: alice | last post by:
Hi, When I compiles the following program with g++, it gives the following output: # g++ -o list list.C list.C: In function `int main()': list.C:116: jump to case label list.C:110: crosses initialization of `std::string data' list.C:120: jump to case label list.C:110: crosses initialization of `std::string data'
5
1911
by: crunix | last post by:
Hello. I have developed a medical application with php 4 linked to IBM DB2 database. The database connection is right and i can access data with no problem...but sometimes when i reload the page which has been already loaded (by pressing CTRL-R) i receive an SQL STATE Error: "(...) SQL State: X (..)"
8
1912
by: G Patel | last post by:
Can people please comment on the layout/style of my problem? The major issue I had was the layout. I ended up having to put a relatively large switch statement, inside an if statement, which is inside a while loop. If someone can tell me how I can rearrange these elements a little to make it cleaner, I would appreciate that. I've tested it...
3
1051
by: Val | last post by:
In vc7 (studio 2002), when I try to debug the first "if" statement, the IDE jumps to the next valid line and evaluates it even if the if-statement is false. What is going on? if( (theDealer.m_nPoints == 15) && (theDealer.Hand.size() == 2) ) //Break Point set here but... { vector<Card>::iterator vdi; // ... runs to here once debugging starts....
4
1375
by: Peter Afonin | last post by:
Hello, I have a weirdest issue I've ever had. I have a function that enters some data into the Oracle table and returns the sequential row number for the new record (autonumber): Private Function AddSystem(ByVal txt As TextBox, ByVal cn As OracleConnection) As Integer Try
5
2403
by: Frederick Dean | last post by:
Hi,guys! I'm reading Stephen Dewhurst's book "C++ Gotchas"£¬in gothca #7, I meet a weird case: bool Postorder::next() { switch (pc) case START: while (true) if (!child()) { pc = LEAF; return true;
5
1701
by: Pupeno | last post by:
Hello, I am experiencing a weird behavior that is driving me crazy. I have module called Sensors containing, among other things: class Manager: def getStatus(self): print "getStatus(self=%s)" % self return {"a": "b", "c": "d"} and then I have another module called SensorSingleton that emulates the
11
1374
by: ssecorp | last post by:
I am never redefining the or reassigning the list when using validate but since it spits the modified list back out that somehow means that the modified list is part of the environment and not the old one. i thought what happend inside a function stays inside a function meaning what comes out is independent of what comes in. Meaning if I want...
0
7703
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...
0
7618
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...
0
7926
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. ...
0
8138
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...
0
7983
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...
1
5514
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...
0
3657
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...
1
1228
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
0
946
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...

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.