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 12 3187
"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.
"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
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!
} 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
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.
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 :-) )
--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;
}
> 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 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 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.
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.
> 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). This thread has been closed and replies have been disabled. Please start a new discussion. Similar topics
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...
|
by: JKop |
last post by:
unsigned int CheesePlain(void)
{
unsigned int const chalk = 42;
return chalk;
}
unsigned int& CheeseRef(void)
{
|
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...
|
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...
|
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...
|
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:
...
|
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...
|
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...
|
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...
|
by: erikbower65 |
last post by:
Using CodiumAI's pr-agent is simple and powerful. Follow these steps:
1. Install CodiumAI CLI: Ensure Node.js is installed, then run 'npm install -g codiumai' in the terminal.
2. Connect to...
|
by: linyimin |
last post by:
Spring Startup Analyzer generates an interactive Spring application startup report that lets you understand what contributes to the application startup time and helps to optimize it. Support for...
|
by: erikbower65 |
last post by:
Here's a concise step-by-step guide for manually installing IntelliJ IDEA:
1. Download: Visit the official JetBrains website and download the IntelliJ IDEA Community or Ultimate edition based on...
|
by: kcodez |
last post by:
As a H5 game development enthusiast, I recently wrote a very interesting little game - Toy Claw ((http://claw.kjeek.com/))。Here I will summarize and share the development experience here, and hope it...
|
by: isladogs |
last post by:
The next Access Europe meeting will be on Wednesday 6 Sept 2023 starting at 18:00 UK time (6PM UTC+1) and finishing at about 19:15 (7.15PM)
The start time is equivalent to 19:00 (7PM) in Central...
|
by: Taofi |
last post by:
I try to insert a new record but the error message says the number of query names and destination fields are not the same
This are my field names
ID, Budgeted, Actual, Status and Differences
...
|
by: lllomh |
last post by:
Define the method first
this.state = {
buttonBackgroundColor: 'green',
isBlinking: false, // A new status is added to identify whether the button is blinking or not
}
autoStart=()=>{
|
by: lllomh |
last post by:
How does React native implement an English player?
|
by: DJRhino |
last post by:
Was curious if anyone else was having this same issue or not....
I was just Up/Down graded to windows 11 and now my access combo boxes are not acting right. With win 10 I could start typing...
| |