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

Catching return value in a const reference needed?

Hello, consider this complete program:
#include <iostream>
#include <string>

using std::cout;
using std::endl;
using std::string;

class Hanna
{
public:
Hanna(const string& s)
:
s_(s)
{ cout << "normal ctor, name = " << s_ << endl; }

Hanna(const Hanna& inst)
:
s_(inst.s_)
{ cout << "copyctor, name = " << s_ << endl; }

~Hanna() { cout << "cleaning up " << s_ << endl; }

Hanna& operator=(const Hanna& rhs)
{
s_ = rhs.s_;

cout << "in operator=(), name = " << s_ << endl;

return *this;
}

private:
string s_;
};

static Hanna
func(const string& s)
{
Hanna anobj(s);

return anobj;
}

int
main()
{
cout << "Testing catching return value in normal object." << endl;

{
Hanna a = func("not catching const ref");

(void)a;
}

cout << "\nTesting catching return value in a const reference" <<
endl;

{
const Hanna& b = func("catching const ref");

(void)b;
}

return 0;
}
When run, the outut is:
$ ./runme
Testing catching return value in normal object.
normal ctor, name = not catching const ref
cleaning up not catching const ref

Testing catching return value in a const reference
normal ctor, name = catching const ref
cleaning up catching const ref

The program has been compiled with optimizations disabled (and
debugging turned on). I thought that I had to catch the return value in
a const reference (if possible), if I wanted to avoid ctor/dtor calls
but seems I dont have to...is this optimization part of the C++
specification?

/ E

Apr 8 '06 #1
2 2320
static Hanna
func(const string& s)
{
Hanna anobj(s);

Here you create a local object of the type "Hanna".

return anobj;

Here you return a local object (by value) of the type "Hanna".

}

int
main()
{
cout << "Testing catching return value in normal object." << endl;

{
Hanna a = func("not catching const ref");

For clarity, maybe change that to:

Hanna a = func("Initialising local object with return value");

(void)a;
}

cout << "\nTesting catching return value in a const reference" <<
endl;

{
const Hanna& b = func("catching const ref");

Hanna b = func("Binding return value to a local const reference");

(void)b;
}

return 0;
}
When run, the outut is:
$ ./runme
Testing catching return value in normal object.
normal ctor, name = not catching const ref
cleaning up not catching const ref

Testing catching return value in a const reference
normal ctor, name = catching const ref
cleaning up catching const ref

The program has been compiled with optimizations disabled (and
debugging turned on). I thought that I had to catch the return value in
a const reference (if possible), if I wanted to avoid ctor/dtor calls
but seems I dont have to...is this optimization part of the C++
specification?

Yes, it's called something like "Eliding constructors"; it's an
optimization. The compiler though doesn't have to perform this optimization.
Without it, I would expect there to be three objects created rather than
one:

1) The local object in "func".

2) The object returned from "func".

3) The local object in "main".
If you only need a const object, I would advocate going the const reference
route.

If you need a non-const object, you could do what you have done, or you
could go for more elaborate means.

-Tomás
Apr 8 '06 #2
Eric Lilja wrote:
Hello, consider this complete program:
#include <iostream>
#include <string>

using std::cout;
using std::endl;
using std::string;

class Hanna
{
public:
Hanna(const string& s)
:
s_(s)
{ cout << "normal ctor, name = " << s_ << endl; }

Hanna(const Hanna& inst)
:
s_(inst.s_)
{ cout << "copyctor, name = " << s_ << endl; }

~Hanna() { cout << "cleaning up " << s_ << endl; }

Hanna& operator=(const Hanna& rhs)
{
s_ = rhs.s_;

cout << "in operator=(), name = " << s_ << endl;

return *this;
}

private:
string s_;
};

static Hanna
Prefer placing functions like that in an unnamed namespace. Using
'static' with functions has been deprecated.
func(const string& s)
{
Hanna anobj(s);

return anobj;
}

int
main()
{
cout << "Testing catching return value in normal object." << endl;

{
Hanna a = func("not catching const ref");

(void)a;
}

cout << "\nTesting catching return value in a const reference" <<
endl;

{
const Hanna& b = func("catching const ref");

(void)b;
}

return 0;
}
When run, the outut is:
$ ./runme
Testing catching return value in normal object.
normal ctor, name = not catching const ref
cleaning up not catching const ref

Testing catching return value in a const reference
normal ctor, name = catching const ref
cleaning up catching const ref

The program has been compiled with optimizations disabled (and
debugging turned on). I thought that I had to catch the return value
in a const reference (if possible), if I wanted to avoid ctor/dtor
calls but seems I dont have to...is this optimization part of the C++
specification?


Yes. The compiler is allowed to optimise away creation of a temporary
when copy-constructing objects. The statement

Hanna a = func();

can end up optimised in such way that there is no temporary and the
function's return value is placed directly in the object being born.

V
--
Please remove capital As from my address when replying by mail
Apr 8 '06 #3

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

Similar topics

19
by: Christian Engström | last post by:
If you have a function that returns something by value, the gcc compiler (version 3.2.3 on Windows XP with MinGW) converts the returned value from the type you specify in the code, to the const...
14
by: Gama Franco | last post by:
Hi, I'm designing an interface for a shared library, and I would like to know if there is a standard about how to return an object to the user. I will use exceptions to report errors, so there...
4
by: Biff | last post by:
Is there a common way to check for vector indexes being in bounds? My version of the STL has no such check, even in debug builds. I was considering deriving a class from Vector with its own...
29
by: pmatos | last post by:
Hi all, Sometimes I have a function which creates an object and returns it. Some are sets, other vectors but that's not very important. In these cases I do something like this: vector<int> *...
2
by: Anders Borum | last post by:
Hello! I was looking at marking objects with a changed state, once properties have been changed. The reason behind this is, that I would like to enlist such objects for processing in a...
32
by: Axel Bock | last post by:
Hi all, I am trying to get my head around what happens if I return a class object from a function. It seems C++ (MinGW) does not invoke the copy constructor if I do something like this: ...
12
by: huangshan | last post by:
hi all In what condition i need( or mast) a (templates)function return value by reference? can you give me a example thanks
5
by: [rob desbois] | last post by:
Consider the following code: try { // throws exceptions of several types Foo(); } catch (out_of_range& ex) { } catch (exception& ex)
10
by: flopbucket | last post by:
Hi, Is this legal? std::string foo() { std::string xyz = "FOO"; return xyz; }
0
by: DolphinDB | last post by:
Tired of spending countless mintues downsampling your data? Look no further! In this article, you’ll learn how to efficiently downsample 6.48 billion high-frequency records to 61 million...
0
by: ryjfgjl | last post by:
ExcelToDatabase: batch import excel into database automatically...
1
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
0
by: Vimpel783 | last post by:
Hello! Guys, I found this code on the Internet, but I need to modify it a little. It works well, the problem is this: Data is sent from only one cell, in this case B5, but it is necessary that data...
0
by: jfyes | last post by:
As a hardware engineer, after seeing that CEIWEI recently released a new tool for Modbus RTU Over TCP/UDP filtering and monitoring, I actively went to its official website to take a look. It turned...
1
by: PapaRatzi | last post by:
Hello, I am teaching myself MS Access forms design and Visual Basic. I've created a table to capture a list of Top 30 singles and forms to capture new entries. The final step is a form (unbound)...
1
by: Shællîpôpï 09 | last post by:
If u are using a keypad phone, how do u turn on JavaScript, to access features like WhatsApp, Facebook, Instagram....
0
by: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 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 former...

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.