473,394 Members | 1,724 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,394 software developers and data experts.

another copy constructor question

Hi,

I was wondering why in the following piece of code, the function test1
calls a copy constructor at return and why test2 does not. Is the usage
of multiple return statements in one function not really a good
programming style?

Thanks for the help

#include <iostream>

class foo {
public:
foo() { };
foo(const foo &c) { std::cout << "copu" << std::endl; }
};

foo test1() {
if (true) {
foo c;
return c;
}
return foo();
}

foo test2() {
foo c;
if (true) {
}
return c;
}

int main(void) {
std::cout << "test 1" << std::endl;
test1();
std::cout << "test 2" << std::endl;
test2();
return 0;
}
Jun 27 '08 #1
12 1299
ciccio wrote:
I was wondering why in the following piece of code, the function test1
calls a copy constructor at return and why test2 does not. Is the usage
of multiple return statements in one function not really a good
programming style?

Thanks for the help

#include <iostream>

class foo {
public:
foo() { };
foo(const foo &c) { std::cout << "copu" << std::endl; }
};

foo test1() {
if (true) {
foo c;
return c;
}
return foo();
}

foo test2() {
foo c;
if (true) {
}
return c;
}

int main(void) {
std::cout << "test 1" << std::endl;
test1();
std::cout << "test 2" << std::endl;
test2();
return 0;
}
I believe in this case it comes down to the compiler's ability to
optimise the copying away. In one case it can, in the other it cannot,
and that's about it. As to the style of multiple return points, it's up
to the user. Too many moons ago I was taught structured programming,
and a single return point was important. Nowadays if you program using
the RAII paradigm, multiple returns are perfectly OK, AFAICT.

V
--
Please remove capital 'A's when replying by e-mail
I do not respond to top-posted replies, please don't ask
Jun 27 '08 #2
On Jun 3, 1:06 pm, Victor Bazarov <v.Abaza...@comAcast.netwrote:
ciccio wrote:
I was wondering why in the following piece of code, the function test1
calls a copy constructor at return and why test2 does not. Is the usage
of multiple return statements in one function not really a good
programming style?
Thanks for the help
#include <iostream>
class foo {
public:
foo() { };
foo(const foo &c) { std::cout << "copu" << std::endl; }
};
foo test1() {
if (true) {
foo c;
return c;
}
return foo();
}
foo test2() {
foo c;
if (true) {
}
return c;
}
int main(void) {
std::cout << "test 1" << std::endl;
test1();
std::cout << "test 2" << std::endl;
test2();
return 0;
}

I believe in this case it comes down to the compiler's ability to
optimise the copying away. In one case it can, in the other it cannot,
and that's about it. As to the style of multiple return points, it's up
to the user. Too many moons ago I was taught structured programming,
and a single return point was important. Nowadays if you program using
the RAII paradigm, multiple returns are perfectly OK, AFAICT.

V
--
Please remove capital 'A's when replying by e-mail
I do not respond to top-posted replies, please don't ask
Take a look on the link below where Sutter explain it

http://www.gotw.ca/gotw/002.htm

Note that the question is not regarding performance, it is just about
why in one case the constructor is called and in another it is not.

AZanetti
Jun 27 '08 #3
ademirzanetti wrote:
On Jun 3, 1:06 pm, Victor Bazarov <v.Abaza...@comAcast.netwrote:
>ciccio wrote:
>>I was wondering why in the following piece of code, the function test1
calls a copy constructor at return and why test2 does not. Is the usage
of multiple return statements in one function not really a good
programming style?
Thanks for the help
#include <iostream>
class foo {
public:
foo() { };
foo(const foo &c) { std::cout << "copu" << std::endl; }
};
foo test1() {
if (true) {
foo c;
return c;
}
return foo();
}
foo test2() {
foo c;
if (true) {
}
return c;
}
int main(void) {
std::cout << "test 1" << std::endl;
test1();
std::cout << "test 2" << std::endl;
test2();
return 0;
}
I believe in this case it comes down to the compiler's ability to
optimise the copying away. In one case it can, in the other it cannot,
and that's about it. As to the style of multiple return points, it's up
to the user. Too many moons ago I was taught structured programming,
and a single return point was important. Nowadays if you program using
the RAII paradigm, multiple returns are perfectly OK, AFAICT.

V
--
Please remove capital 'A's when replying by e-mail
I do not respond to top-posted replies, please don't ask

Take a look on the link below where Sutter explain it

http://www.gotw.ca/gotw/002.htm

Note that the question is not regarding performance, it is just about
why in one case the constructor is called and in another it is not.

AZanetti
Not sure what your point was or whether you replied to me or to the OP.
Perhaps you could explain what parts of Sutter's GotW #2 apply here and
how. Much appreciated.

V
--
Please remove capital 'A's when replying by e-mail
I do not respond to top-posted replies, please don't ask
Jun 27 '08 #4
On Jun 3, 6:06 pm, Victor Bazarov <v.Abaza...@comAcast.netwrote:
ciccio wrote:
I was wondering why in the following piece of code, the
function test1 calls a copy constructor at return and why
test2 does not. Is the usage of multiple return statements
in one function not really a good programming style?
Thanks for the help
#include <iostream>
class foo {
public:
foo() { };
foo(const foo &c) { std::cout << "copu" << std::endl; }
};
foo test1() {
if (true) {
foo c;
return c;
}
return foo();
}
foo test2() {
foo c;
if (true) {
}
return c;
}
int main(void) {
std::cout << "test 1" << std::endl;
test1();
std::cout << "test 2" << std::endl;
test2();
return 0;
}
I believe in this case it comes down to the compiler's ability
to optimise the copying away. In one case it can, in the
other it cannot, and that's about it.
In the end, yes. Probably, the compiler sees that there are
branches which don't return c, and so does not apply NVRO,
although it conceivably could, because in every case c is
constructed, it is the return value.
As to the style of multiple return points, it's up to the
user. Too many moons ago I was taught structured programming,
and a single return point was important. Nowadays if you
program using the RAII paradigm, multiple returns are
perfectly OK, AFAICT.
If you don't care about readable or correct code.

In practice, functions should be small enough that the impact on
readability or correction are minor; there are certainly larger
issues. And there are also special cases where it is
acceptable, or maybe even preferred (a function which consists
of a single switch, with a return in each case). But as a
general rule, its better to avoid.

--
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
Jun 27 '08 #5
Hi!

James Kanze schrieb:
In practice, functions should be small enough that the impact on
readability or correction are minor; there are certainly larger
issues. And there are also special cases where it is
acceptable, or maybe even preferred (a function which consists
of a single switch, with a return in each case). But as a
general rule, its better to avoid.
Reminds me of the ugly:

int foo(int param)
{
int result;
if(bar(param))
{
result = 10;
}
else
{
result = -5;
}
return result;
}

there is mode code necessary to handle the SESE (single entry, single
exit) than there is for actual behaviour. I can't stand it. It's not
readable in my opinion.

Frank
Jun 27 '08 #6
In article <6a*************@mid.dfncis.de>, bl************@gmx.net
says...

[ ... ]
int foo(int param)
{
int result;
if(bar(param))
{
result = 10;
}
else
{
result = -5;
}
return result;
}

there is mode code necessary to handle the SESE (single entry, single
exit) than there is for actual behaviour. I can't stand it. It's not
readable in my opinion.
This can be made SESE with no flow-control at all:

int foo(int param) {
int rets[-5, 10];

return rets[(bool)bar(param)];
}

No code for anything but the values and the behavior.

--
Later,
Jerry.

The universe is a figment of its own imagination.
Jun 27 '08 #7
In article <Zc******************************@posted.comnet> ,
al***@start.no says...
* Jerry Coffin:
[ ... ]
int foo(int param) {
int rets[-5, 10];

return rets[(bool)bar(param)];
}

Uhm, I think you must have been coding in some other language recently... ;-)
Nope -- my fondness for such things isn't recent at all. To a large
extent it goes back to my days writing Fortran. Its (nearly) complete
lack of control structures made such code seem quite reasonable.
Anyways, as implicit in my article else-thread, I'd simply use a conditional
expression rather than a look-up.
That's certainly an option, of course. I'll openly admit I'm fond of the
table driven version, quite possibly to an inordinate degree.
That is, if I chose to make this a function at all.
Well yes, there is that. As it stands right now, it looks like a pretty
worthless function, but it was clearly written more to make a point than
with any real purpose in mind. The problem is that in many cases, by the
time you make it useful, the point he was trying to make is like to
disappear.

--
Later,
Jerry.

The universe is a figment of its own imagination.
Jun 27 '08 #8
On Jun 5, 12:42 am, Frank Birbacher <bloodymir.c...@gmx.netwrote:
James Kanze schrieb:
In practice, functions should be small enough that the impact on
readability or correction are minor; there are certainly larger
issues. And there are also special cases where it is
acceptable, or maybe even preferred (a function which consists
of a single switch, with a return in each case). But as a
general rule, its better to avoid.
Reminds me of the ugly:
int foo(int param)
{
int result;
if(bar(param))
{
result = 10;
}
else
{
result = -5;
}
return result;
}
In that case, the obvious way to write the function is:

int
foo( int param )
{
return bar( param ) ? 10 : -5 ;
}

Anything else is obfuscation.

If the branches become more complex, however, then using the
result variable certainly improves readability.

--
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
Jun 27 '08 #9
On Jun 5, 2:13 am, Jerry Coffin <jcof...@taeus.comwrote:
In article <6aok2tF38n2s...@mid.dfncis.de>, bloodymir.c...@gmx.net
says...
[ ... ]
int foo(int param)
{
int result;
if(bar(param))
{
result = 10;
}
else
{
result = -5;
}
return result;
}
there is mode code necessary to handle the SESE (single entry, single
exit) than there is for actual behaviour. I can't stand it. It's not
readable in my opinion.
This can be made SESE with no flow-control at all:
int foo(int param) {
int rets[-5, 10];
I presume that here you meant:

static int const rets[] = { -5, 10 } ;
return rets[(bool)bar(param)];
}
No code for anything but the values and the behavior.
I don't know. I often use something similar instead of a
switch. But somehow the idea of indexing with "bool" doesn't
appeal to me---you're really counting on something that is only
present for hister^H^Horical reasons: the fact that conversion
of bool to int is guaranteed to return 0 and 1. (*IF* for some
reason I needed to index with a bool, I'd probably write it out
in full: "theBool ? 1 : 0". Conceptually, a bool is NOT an
integral value, regardless of what the language standard says.)

--
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
Jun 27 '08 #10
Hi!

Alf P. Steinbach schrieb:
Not that I don't agree with your implied conclusion, that fanatical
adherence to SESE is ungood (epecially in C++), but your example doesn't
hold water: for this example, SESE produces the least code, namely 1
line function body, whereas SEME produces at least 2 lines and depending
on formatting in general twice that.

int foo( int param )
{
return (bar( param )? 10 : -5);
}
Yes, you are right. I figured I'm actually mixing two things here: SESE
and some programming style. But both to serve the same purpose, that is
"easier" debugging.

I was handed in some code like I posted. I replied the code could be
much easier, e.g. like "return bar(param) ? 10 : -5;". It would be much
shorter, clearer and easier to read. But the author told me about his
former experiences and coding standards he had to use. They would
require explicit curly braces on extra lines and SESE to make debugging
easier because you could actually step through the lines to see which
branch is taken and you could place a single break point at "return" to
see what the "result" was. He was so into it I couldn't even convince
him to replace
if(...)
{
result = true;
}
else
{
result = false;
}

by
result = ...;

and of course not by
return ...;

Personally I couldn't giveup concise code in general to help out a bad
debugger.

Frank
Jun 27 '08 #11
In article <630db2ce-1aee-4a55-a9cb-
44**********@a1g2000hsb.googlegroups.com>, ja*********@gmail.com says...

[ ... ]
int foo(int param) {
int rets[-5, 10];

I presume that here you meant:

static int const rets[] = { -5, 10 } ;
return rets[(bool)bar(param)];
}
Yes, now that you mention it, that does look closer to something a
compiler might accept, doesn't it?
No code for anything but the values and the behavior.

I don't know. I often use something similar instead of a
switch. But somehow the idea of indexing with "bool" doesn't
appeal to me---you're really counting on something that is only
present for hister^H^Horical reasons: the fact that conversion
of bool to int is guaranteed to return 0 and 1. (*IF* for some
reason I needed to index with a bool, I'd probably write it out
in full: "theBool ? 1 : 0". Conceptually, a bool is NOT an
integral value, regardless of what the language standard says.)
I dunno -- I don't really see a problem with it. I think before I
explicitly converted the bool to an integer, I'd create a tiny (mostly
NOP) class that acted a bit like an array, but took a bool as a
subscript.

--
Later,
Jerry.

The universe is a figment of its own imagination.
Jun 27 '08 #12
In article <na******************************@posted.comnet> ,
al***@start.no says...

[ ... ]
Well, I must admit that rather than being fond of error messages, I tend to be
annoyed by them. ;-)
Obviously, when I'm tired I can miss even the _extremely_ obvious...

--
Later,
Jerry.

The universe is a figment of its own imagination.
Jun 27 '08 #13

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

Similar topics

7
by: Christian Engström | last post by:
When i compile the program listed below with gcc version 3.3.1 (MinGW on Windows XP) I get the following result: Calling 'func(d)': 'base' copy constructor Calling 'func(*d_handle)': 'base'...
8
by: trying_to_learn | last post by:
Why do we need to explicitly call the copy constructor and the operator = , for base class and member objects in composition? ....book says "You must explicitly call the GameBoard copy-constructor...
14
by: Arne | last post by:
In C++ we have a copy constructor. What is the equivalent in .Net? Would that be a clone method?
11
by: dalu.gelu | last post by:
Hi, can anyone help me by writing a sample code of defining a copy constructor in a class having data member as an object of another class. for eg: class A{ int x; public: A(){ x=6;} };
3
by: subramanian | last post by:
Consider the code fragment: class Test { public: Test(const Test &temp); ... }; ....
19
by: Jeroen | last post by:
Hi guys, I have a simple question. If I have a class like: class A { A(); ~A(); A(A& a); A(int i);
22
by: clicwar | last post by:
A simple program with operator overloading and copy constructor: #include <iostream> #include <string> using namespace std; class Vector { private: float x,y; public: Vector(float u, float...
1
by: Visame | last post by:
#include <iostream> using namespace std; class A { public: A() {cout << "constructor A" << endl;} A(A& a) {cout<<"copy A"<<endl;} virtual void Test(){cout <<"A test"...
6
by: suresh | last post by:
Hi Could you please tell why copy constructor is not called in the first line in main(), as mentioned in the text books. I used g++ version 4.1.2 on debian etch thanks suresh # include...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
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...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
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
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,...
0
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...
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...

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.