473,763 Members | 4,584 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
12 3292
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
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(c onst 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
> 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.


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

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

Similar topics

10
4293
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
1624
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
1840
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
2277
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
3260
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
9386
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10144
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
9937
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
9822
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...
0
6642
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
5270
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...
1
3917
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
3
3522
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2793
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.