By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
449,411 Members | 1,042 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 449,411 IT Pros & Developers. It's quick & easy.

Function Returning a local object???

P: n/a
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
Share this Question
Share on Google+
12 Replies


P: n/a

"Olumide" <50***@web.de> wrote in message
news:c8**************************@posting.google.c om...
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

P: n/a

"Olumide" <50***@web.de> wrote in message
news:c8**************************@posting.google.c om...
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

P: n/a
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

P: n/a
50***@web.de (Olumide) wrote in
news:c8**************************@posting.google.c om:
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

P: n/a
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

P: n/a
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

P: n/a
--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

P: n/a
>
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::operator= (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

P: n/a
50***@web.de (Olumide) wrote in message news:<c8**************************@posting.google. 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

P: n/a
50***@web.de (Olumide) wrote:
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.)


Actually the copy constructor is used here, "newly created
variables" includes temporary objects. When the function
returns, a temporary object is created (in the scope of the
calling function) using the copy-constructor, with the returned
value as parameter.
The calling function usually does something with this object,
eg. if it initializes another object then the copy-constructor
will be called again, with the temporary return-value object as
a parameter.
Being a temporary object, it will be destroyed at the end of the
full-expression it was created in, eg if we have at local scope:

Foo func() { Foo g; return g; }
Foo f( func() );

then we have:
- g is default-constructed
- temporary return value is copy-constructed from g
- g is destroyed
- f is copy-constructed from temporary return-value
- temporary return-value is destroyed

The compiler is allowed to optimise all this, so you can't test
it with a compiler, but if you make Foo with a private copy
constructor then it should fail to compile.
Jul 22 '05 #11

P: n/a
Old Wolf wrote:
Olumide wrote:
I know its ok to return by value -
for simple data types for example:

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

int 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 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.
Your suspicions are unfounded.
My question therefore, "How is this all the necessary copying handled?"
No copying is required.

Suppose, instead, that you write:

MFVec foo(const MFVec& z1, const MFVec& z2) {
MFVec res = z1;
res += z2
return res;
}

In the typical implementation, the compiler will emit code similar to:

MFVec& foo(MFVec& res, const MFVec& z1, const MFVec& z2) {
res = z1; // using the copy constructor
res += z2;
return res;
}

In other words,
the compiler creates the return value in the calling program
and passes a [hidden] reference to it to function foo.
Function foo does *not* create a local object named res
but recognizes that res is another name for the return value.

This is especially efficient if you use foo to initialize an object
in the calling program:

MFVec z3 = foo(z1, z2);

The compiler emits code to allocate storage for z3
that passes a reference to z3 as a hidden argument to foo
which foo interprets as a reference to the return value --
z3 is initialized by foo directly and no temporary is required.
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.)

Actually the copy constructor is used here, "newly created
variables" includes temporary objects. When the function
returns, a temporary object is created (in the scope of the
calling function) using the copy-constructor, with the returned
value as parameter.
The calling function usually does something with this object,
eg. if it initializes another object then the copy-constructor
will be called again, with the temporary return-value object as
a parameter.
Being a temporary object, it will be destroyed at the end of the
full-expression it was created in, eg if we have at local scope:

Foo func() { Foo g; return g; }
Foo f( func() );

then we have:
- g is default-constructed
- temporary return value is copy-constructed from g
- g is destroyed
- f is copy-constructed from temporary return-value
- temporary return-value is destroyed

The compiler is allowed to optimise all this, so you can't test
it with a compiler, but if you make Foo with a private copy
constructor then it should fail to compile.


Let's try that:
cat main.cc #include <iostream>

class Foo {
private:
// representation
int I;
public:
// operators
Foo& operator=(const Foo& foo) {
I = foo.I;
std::cout << "Foo::operator=(const Foo&)" << std::endl;
return *this;
}
friend
std::ostream& operator<<(std::ostream& os, const Foo& foo);
// constructors
Foo(int i = 0): I(i) {
std::cout << "Foo::Foo(int)\tI = " << I << std::endl;
}
Foo(const Foo& foo): I(foo.I) {
std::cout << "Foo::Foo(const Foo&)" << std::endl;
}
~Foo(void) {
std::cout << "Foo::~Foo(void)" << std::endl;
}
};

Foo func(void) {
Foo g;
g = Foo(13);
std::cout << "func(void)" << std::endl;
return g;
}

inline
std::ostream& operator<<(std::ostream& os, const Foo& foo) {
return os << foo.I;
}

int main(int argc, char* argv[]) {
Foo f(func());
std::cout << "f = " << f << std::endl;
return 0;
}
g++ -Wall -ansi -pedantic -o main main.cc
./main

Foo::Foo(int) I = 0
Foo::Foo(int) I = 13
Foo::operator=(const Foo&)
Foo::~Foo(void)
func(void)
f = 13

I defined a copy constructor but it was never called.
Notice that I modified func(void)
to assign a new value to g before it returns.
Function func(void) initializes object f in function main
directly using the default constructor Foo(int i = 0)
then it constructs a temporary Foo(13)
and assigns this temporary value to object f directly.
Finally, function func(void) destroys the temporary
just before it returns. No destructor is required for g
because g is just another name for the return value
which, in this case, is just object f in function main.
Jul 22 '05 #12

P: n/a
> Not true, it does member copying.

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

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

Same principle for copy constructor.


Yes my mistake (shouldn't be discussing while writing a reply).
Jul 22 '05 #13

This discussion thread is closed

Replies have been disabled for this discussion.