Function Returning a local object???

O

Olumide

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
 
E

E. Robert Tisdale

Olumide said:
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!
}
 
R

Rich Herrick

Olumide said:
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.
 
D

Dave Townsend

Olumide said:
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
 
E

E. Robert Tisdale

Dave said:
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/archive/2004/02/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.
 
G

Gregg

(e-mail address removed) (Olumide) wrote in
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
 
O

Olumide

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 :) )
 
V

velthuijsen

--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;
}
 
J

John Harrison

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::eek:perator= will copy the member y using std::string::eek:perator= (this is
not a byte copy), and will also copy the member z (this is a byte copy).

Same principle for copy constructor.

john
 
G

Gregg

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
 
O

Old Wolf

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.
 
E

E. Robert Tisdale

Your suspicions are unfounded.

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.
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::eek:perator=(const Foo&)" << std::endl;
return *this;
}
friend
std::eek:stream& operator<<(std::eek:stream& 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::eek:stream& operator<<(std::eek:stream& 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::eek:perator=(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.
 
V

velthuijsen

Not true, it does member copying.
class X
{
std::string y;
int z;
};

X::eek:perator= will copy the member y using std::string::eek:perator= (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).
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
474,175
Messages
2,570,947
Members
47,498
Latest member
yelene6679

Latest Threads

Top