473,748 Members | 9,416 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Function Returning a local object???

I'm studying Nigel Chapman's Late Night Guide to C++ which I think is
an absolutely fantastic book; however on page 175 (topic: operator
overlaoding), there the following code snippet:

inline MFVec operator+(const MFVec& z1, const MFVec& z2) // Global
function
{
MFVec res = z1;
res += z2
return res; // WHY???
}

MFVec is the (vector) class:

class MFVec {
public:
MFVec(float x, float y);
// other member functions
private:
float xcoord, ycoord;
}

My problem however lies with the line 3 of the global operator+()
function because it returns the local variable res, which I assume is
destroyed as soon as the function is exited. This resembles a dangling
refrence and I don't know why its not illegal. Anyone knows why?

I don't mind thorough answers; in fact I kidda prefer them ;-)

Thanks

- Olumide
Jul 22 '05 #1
12 3291

"Olumide" <50***@web.de > wrote in message
news:c8******** *************** ***@posting.goo gle.com...
I'm studying Nigel Chapman's Late Night Guide to C++ which I think is
an absolutely fantastic book; however on page 175 (topic: operator
overlaoding), there the following code snippet:

inline MFVec operator+(const MFVec& z1, const MFVec& z2) // Global
function
{
MFVec res = z1;
res += z2
return res; // WHY???
}

MFVec is the (vector) class:

class MFVec {
public:
MFVec(float x, float y);
// other member functions
private:
float xcoord, ycoord;
}

My problem however lies with the line 3 of the global operator+()
function because it returns the local variable res, which I assume is
destroyed as soon as the function is exited. This resembles a dangling
refrence and I don't know why its not illegal. Anyone knows why?

I don't mind thorough answers; in fact I kidda prefer them ;-)

Thanks

- Olumide


The code is fine. It is not returning the local, but a copy. The return
type is the class, not a reference.

Jul 22 '05 #2

"Olumide" <50***@web.de > wrote in message
news:c8******** *************** ***@posting.goo gle.com...
I'm studying Nigel Chapman's Late Night Guide to C++ which I think is
an absolutely fantastic book; however on page 175 (topic: operator
overlaoding), there the following code snippet:

inline MFVec operator+(const MFVec& z1, const MFVec& z2) // Global
function
{
MFVec res = z1;
res += z2
return res; // WHY???
}

MFVec is the (vector) class:

class MFVec {
public:
MFVec(float x, float y);
// other member functions
private:
float xcoord, ycoord;
}

My problem however lies with the line 3 of the global operator+()
function because it returns the local variable res, which I assume is
destroyed as soon as the function is exited. This resembles a dangling
refrence and I don't know why its not illegal. Anyone knows why?

I don't mind thorough answers; in fact I kidda prefer them ;-)

Thanks
No, this code is righteous, its ok to return an object, although the object
"res"will
be destroyed it will be copied and the copy returned to you ( but
compilers
will generally optimize this sequence and return the actual res to you and
not destroy it).
The example you quote is idiomatic in the sense that it is the pattern used
to
implement classes which define the + operation such as complex numbers,
vectors, etc.
You can check this by looking at the "this" pointer for the "res" object and
the returned
object, they should be different ( or at least in debug compile mode).

You might be confusing returning references to local objects. This is pure
evil...
once the function returns the value, the object is destroyed and you are
hanging onto
a invalid reference. For instance :

foo& getfoo(){ foo f; return f;}
....
foo& g = getfoo(); // f is not a valid object anymore now so g is not a
valid reference...

You can put in some debug printfs in the constructors, destructors, and you
should
see that the reference you are getting back is already toasted.

Sometimes you will see member functions of a class returning
references to objects, this is ok when the objects in question are data
members of the
object - these are not local objects because they exist for the lifetime of
the owning
object they belong to - although this approach is questionable when the
object itself may be relocated
and destroyed/invalidated ( such as in STL container classes). In such
circumstances you might
need to copy or process the return value immediately before its destroyed or
invalidated.

dave


- Olumide

Jul 22 '05 #3
Olumide wrote:
I'm studying Nigel Chapman's Late Night Guide to C++
which I think is an absolutely fantastic book; however, on page 175,
(topic: operator overloading), there the following code snippet:

inline
MFVec operator+(const MFVec& z1, const MFVec& z2) {
// Globalfunction
MFVec res = z1;
res += z2
return res; // WHY???
}

MFVec is the (vector) class:

class MFVec {
public:
MFVec(float x, float y);
// other member functions
private:
float xcoord, ycoord;
};

My problem however lies with the line 3 of the global operator+()
function because it returns the local variable res,
which I assume is destroyed as soon as the function is exited.
This resembles a dangling refrence
and I don't know why its not illegal.
Anyone knows why?


operator+(const MFVec&, const MFVec&)
returns a *value* not a *reference*.
To return a reference, you must write:

inline
MFVec& operator+(const MFVec& z1, const MFVec& z2) {
// Global function
MFVec res = z1;
res += z2
return res; // Bad idea!
}
Jul 22 '05 #4
50***@web.de (Olumide) wrote in
news:c8******** *************** ***@posting.goo gle.com:
inline MFVec operator+(const MFVec& z1, const MFVec& z2) // Global
function
{
MFVec res = z1;
res += z2
return res; // WHY???
} My problem however lies with the line 3 of the global operator+()
function because it returns the local variable res, which I assume is
destroyed as soon as the function is exited. This resembles a dangling
refrence and I don't know why its not illegal. Anyone knows why?


This is fine. It is returning a copy of the local, not a reference or
pointer to the local (which would have the problem you mentioned). After
all, would you have trouble with

inline int plus(const int& a1, const int& a2)
{
int res = a1;
res += a2;
return res;
}

(other than the unusual argument type const int&)

Gregg
Jul 22 '05 #5
Dave Townsend wrote:
It's ok to return an object.
Although the object "res" will be destroyed,
it will be copied and the copy returned to you.
(But compilers will generally optimize this sequence
and return the actual res to you and not destroy it.)


This is called the Named Return Value Optimization (NRVO).

http://blogs.msdn.com/slippman/archi.../03/66739.aspx

The compiler recognizes that
"res" is actually a reference to the return value
and initializes the return value directly.
No local object is constructed
so it doesn't need to be destroyed either.
Jul 22 '05 #6
Ok guys, thanks for the answers. I know its ok to return by value -
for simple data types for example:

int foo(){
int number = 5;
return 5;
}

int bar;
bar = foo();

This is no problem, because I can imagine the return value of foo()
i.e. 5, being copied to the integer bar. But when the foo() returns a
derived class class whose member variables are themselves class
objects or worse still objects(?) of a derived class, I suspect there
will be a fair amount of copying taking place when foo returns such a
class by value. My question therefore how is this all the necessary
copying handled??? By the overlaoded assignament operator, operator= ?
If so, what happens is this operator= has not been defined by the
programmer. Is it generated by the compiler? (I've read enough to know
that the copy constructor is only invloved in the initialization of
newly created variables, global or otherwise, but this is not the case
here. All that's happening here is assignment.)

I hope I'm making a bit of sense. Someone please help starigten me
out. I know I'm missing something here.

Thanks,

- Olumide
PS:
Anyone knows Nigel Chapman? (I cant find him online.) Well, tell him
he's written a fantastic book. I've oredered my own copy. (I've kept
the library's for way too long :-) )
Jul 22 '05 #7
--8<----8<----8<----8<----8<----8<----8<----8<----8<----8<----8<--
This is no problem, because I can imagine the return value of foo()
i.e. 5, being copied to the integer bar. But when the foo() returns a
derived class class whose member variables are themselves class
objects or worse still objects(?) of a derived class, I suspect there
will be a fair amount of copying taking place when foo returns such a
class by value. My question therefore how is this all the necessary
copying handled??? By the overlaoded assignament operator, operator= ?
The best way to find out is to write small programs to see what
happens when you try out the different options. At the bottom I've got
a small program to get you started.
If so, what happens is this operator= has not been defined by the
programmer. Is it generated by the compiler? (I've read enough to know
that the copy constructor is only invloved in the initialization of
newly created variables, global or otherwise, but this is not the case
here. All that's happening here is assignment.)


Yes if you do not define the operator= the compiler will provide one
for you. What is does is byte copying. The compiler will also create
the constructor, destructor and copy constructor if you don't defined
them.

#include <iostream>

using std::cout;

static int base = 1;
class Foo
{
public:
Foo(int i = base) {intern = i; cout << intern << " Foo Ctor\n";}
~Foo() { cout << intern << " Foo Dtor\n"; }
Foo(const Foo &Right) {intern = Right.intern; cout << intern << " "
<< Right.intern << " Foo copy Ctor\n"; }
Foo& operator= (const Foo &Right) { cout << intern << " " <<
Right.intern << " Foo operator=\n"; intern = Right.intern; return
*this;}
Foo operator+ (const Foo &Right) { cout << "Foo operator+\n"; Foo
ter(*this); ter.intern += Right.intern; return ter;}
private:
int intern;
};

int main()
{
{
Foo Bar;
++base;
Foo Bar2(Bar);
++base;
Foo Bar3 = Bar2;
++base;
Foo Bar4;
++base;
Foo Bar5;
++base;
Foo Bar6 = Bar5+ Bar4;
++base;
Bar4 = Bar2 = Bar6;
}
getchar();
return 0;
}
Jul 22 '05 #8
>
Yes if you do not define the operator= the compiler will provide one
for you. What is does is byte copying. The compiler will also create
the constructor, destructor and copy constructor if you don't defined
them.


Not true, it does member copying.

class X
{
std::string y;
int z;
};

X::operator= will copy the member y using std::string::op erator= (this is
not a byte copy), and will also copy the member z (this is a byte copy).

Same principle for copy constructor.

john
Jul 22 '05 #9
50***@web.de (Olumide) wrote in message news:<c8******* *************** ****@posting.go ogle.com>...
Ok guys, thanks for the answers. I know its ok to return by value -
for simple data types for example:

int foo(){
int number = 5;
return 5;
}

int bar;
bar = foo();

This is no problem, because I can imagine the return value of foo()
i.e. 5, being copied to the integer bar.
Well here you are not even using the local in the return statement.
class by value. My question therefore how is this all the necessary
copying handled??? By the overlaoded assignament operator, operator= ?
It is handled by the copy constructor, either the default one (which
does a member-wise copy) or an explicitly defined one. Member-wise
copy only does a "shallow" copy, so if a copyable object has members
that are pointers, you will normally be defining your own copy
constructor. Surely the C++ book you have explains this.
If so, what happens is this operator= has not been defined by the
programmer. Is it generated by the compiler? (I've read enough to know
that the copy constructor is only invloved in the initialization of
newly created variables, global or otherwise, but this is not the case
here. All that's happening here is assignment.)


Operator= is not used to construct new objects. It is only used on
existing objects. What looks like an assignment

Foo bar = GetFoo();

is not an assignment. It is an alternative syntax for construction,
and is equivalent to

Foo bar(GetFoo());

An assignent would be something like

Foo bar;
bar = GetFoo();

Then the assignement and/or copy construction may be performed,
depending on what kinds of optimization the compiler performs. You can
use your debugger or print statements to see what is happening,
bearing in mind that turning optimizations off might change how this
is done.

Gregg
Jul 22 '05 #10

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

Similar topics

10
4291
by: Michael | last post by:
Guys, I'm interested in how the compiler implements function calls, can anyone correct my understanding/point me towards some good articles. When a function is called, is the stack pointer incremented by the size of the variables declared in the called function, and then the function will know where these are in memory relative to the current stack pointer position. ALso how are variables returned, is that by a set position in the...
6
1710
by: JKop | last post by:
unsigned int CheesePlain(void) { unsigned int const chalk = 42; return chalk; } unsigned int& CheeseRef(void) {
5
1623
by: Tim Clacy | last post by:
When exiting function scope, which occurs first: a) destruction of local objects b) copy of value for return From disassembly of a debug target, it looks like the return value is copied before local objects are destroyed. Is this standard behaviour? Can the same behaviour be expected for any optimisation level? As an example, in the function 'int A::fn()' here, is 'b' destroyed before 'i' is copied or vice-versa?:
3
1837
by: Milan Gornik | last post by:
Hello to all, My question is on right way of returning newly created class from a function (and thus, from class method or operator). As I currently see it, there are two different ways to do that. One way is to create new class as a local (automatic) variable in function and then to return it:
5
2276
by: Alfonso Morra | last post by:
Hi, What is the recomended way of returning an STL container (e.g. std::string, std::vector etc fom a function? Is it by simply returning a local variable? (I doubt it) std::string foo(const std::string& rhs) { std::string var = rhs ; var += " received" ;
17
3259
by: I.M. !Knuth | last post by:
Hi. I'm more-or-less a C newbie. I thought I had pointers under control until I started goofing around with this: ================================================================================ /* A function that returns a pointer-of-arrays to the calling function. */ #include <stdio.h> int *pfunc(void);
0
1300
by: MikeCS | last post by:
Hi all I would like some help with this issue. I am new to VB 2005 (OK with VB6) My problem is that I cannot seem to return a structure from a function. Example: I defined a structure in a class (from which I instantiated an object). One of the object methods is supposed to return a data record (a structure).
3
5810
by: George2 | last post by:
Hello everyone, 1. Returning non-const reference to function local object is not correct. But is it correct to return const reference to function local object? 2. If in (1), it is correct to return const reference to function local object, the process is a new temporary object is created (based on the function local object) and the const reference is binded to the
5
2680
by: ctj951 | last post by:
I have a very specific question about a language issue that I was hoping to get an answer to. If you allocate a structure that contains an array as a local variable inside a function and return that structure, is this valid? As shown in the code below I am allocating the structure in the function and then returning the structure. I know if the structure contained only simple types (int, float) this will work without problems as you...
0
8984
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
9530
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...
1
9312
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 Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9238
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...
1
6793
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 instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6073
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
4593
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
4864
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
2775
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.