472,992 Members | 3,765 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 472,992 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 2297
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
tracyyun
by: tracyyun | last post by:
Hello everyone, I have a question and would like some advice on network connectivity. I have one computer connected to my router via WiFi, but I have two other computers that I want to be able to...
4
NeoPa
by: NeoPa | last post by:
Hello everyone. I find myself stuck trying to find the VBA way to get Access to create a PDF of the currently-selected (and open) object (Form or Report). I know it can be done by selecting :...
3
NeoPa
by: NeoPa | last post by:
Introduction For this article I'll be using a very simple database which has Form (clsForm) & Report (clsReport) classes that simply handle making the calling Form invisible until the Form, or all...
1
by: Teri B | last post by:
Hi, I have created a sub-form Roles. In my course form the user selects the roles assigned to the course. 0ne-to-many. One course many roles. Then I created a report based on the Course form and...
3
by: nia12 | last post by:
Hi there, I am very new to Access so apologies if any of this is obvious/not clear. I am creating a data collection tool for health care employees to complete. It consists of a number of...
0
NeoPa
by: NeoPa | last post by:
Introduction For this article I'll be focusing on the Report (clsReport) class. This simply handles making the calling Form invisible until all of the Reports opened by it have been closed, when it...
0
isladogs
by: isladogs | last post by:
The next online meeting of the Access Europe User Group will be on Wednesday 6 Dec 2023 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, Mike...
4
by: GKJR | last post by:
Does anyone have a recommendation to build a standalone application to replace an Access database? I have my bookkeeping software I developed in Access that I would like to make available to other...
3
SueHopson
by: SueHopson | last post by:
Hi All, I'm trying to create a single code (run off a button that calls the Private Sub) for our parts list report that will allow the user to filter by either/both PartVendor and PartType. On...

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.