473,794 Members | 2,765 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Function argument lifespan

All,

As the simple sample program below demonstrates, function arguments are
destroyed after the return value of the function has been evaluated. As
opposed to local function variables, which are destroyed before the
function returns.

Is this correct? (To the best of my knowledge it is)
Where in the standard is this described?

Thanks,
Andre

--- Example ---

#include <iostream>

using namespace std;

class test
{
public:
test( string s = "")
: s_(s)
{
cout << "test::test()\t " << s_ << endl;
}

test( const test &org)
{
cout << "test::test(cop y)" << endl;
s_ = "copy of " + org.s_ ;
}

~test()
{
cout << "test::~test()\ t" << s_ << endl;
}

const string & getStr() const
{
return s_;
};

private:
string s_;
};

const test & f( test arg )
{
test l("local");
return arg;
}

int main()
{
test c("main");
cout << "\n\t\tf() = [" << f( c ).getStr() << "]\n" << endl;
}

Oct 19 '05 #1
10 2041
in*****@gmail.c om wrote:
As the simple sample program below demonstrates, function arguments
are destroyed after the return value of the function has been
evaluated. As opposed to local function variables, which are
destroyed before the function returns.

Is this correct? (To the best of my knowledge it is)
Where in the standard is this described?


3.8 Object lifetime, 12.2 Temporary objects. Probably more...

V
Oct 19 '05 #2

Victor Bazarov wrote:
Where in the standard is this described?


3.8 Object lifetime, 12.2 Temporary objects. Probably more...

V


Victor,

Thank you very much for your quick and knowledgable answer!
Much appreciated!

Thanks,
Andre

Oct 19 '05 #3

in*****@gmail.c om wrote:
All,

As the simple sample program below demonstrates, function arguments are
destroyed after the return value of the function has been evaluated. As
opposed to local function variables, which are destroyed before the
function returns.

Is this correct? (To the best of my knowledge it is)
Where in the standard is this described?

Thanks,
Andre

--- Example ---

#include <iostream>

using namespace std;

class test
{
public:
test( string s = "")
: s_(s)
{
cout << "test::test()\t " << s_ << endl;
}

test( const test &org)
{
cout << "test::test(cop y)" << endl;
s_ = "copy of " + org.s_ ;
}

~test()
{
cout << "test::~test()\ t" << s_ << endl;
}

const string & getStr() const
{
return s_;
};

private:
string s_;
};

const test & f( test arg )
{
test l("local");
return arg;
}
The f() routine returns a reference to a function parameter whose
lifetime ends at function exit. Therefore I believe that the behavior
of your program is undefined.
int main()
{
test c("main");
cout << "\n\t\tf() = [" << f( c ).getStr() << "]\n" << endl;
}


I don't believe it's possible to draw any sound conclusions from
running this program due to the implementation of f() above.

Greg

Oct 19 '05 #4
This is nonsense sample, cause f() returns a reference to a temporary
object which is copy of "test arg".

Oct 19 '05 #5
Greg wrote:
const test & f( test arg )
{
test l("local");
return arg;
}


The f() routine returns a reference to a function parameter whose
lifetime ends at function exit. Therefore I believe that the behavior
of your program is undefined.


Actually, I do think the behaviour is defined. My original question was
how to better define why it is legal - i.e. where it is mentionend in
the standard.

Victor pointed me to item 12.2 in the C++ Standard. I believe
paragraphs 2 and onward explain it (too long to reproduce here).

Given the example code (para. 2):
X f(X); // X is a class
...
X a(1);
a=f(a);

The standard writes:
"...the expression a=f(a) requires a temporary for either the
argument 'a' or the result of f(a) to avoid undesired aliasing of 'a'."

B.Stroustrup writes (similar wording to the standard para. 3) in "The
C++ Programming Language", section 10.4.10:
"Unless bound to a reference or used to initialize a named object, a
temporary object is destroyed at the end of the full expression in
which it was created."

IMHO the temporary object (arg) is created as part of the cout <<
f(c)... expression. Thus it exists until the end of that whole
expression (once again IMHO).

Is this not correct?

Cheers,
Andre

Oct 19 '05 #6
aling wrote:
This is nonsense sample,
What part is nonsense?
What is your definition of nonsene in this context?
cause f() returns a reference to a temporary object
That part I agree with...
which is copy of "test arg".


....this part I don't.

A reference to "arg" is returned, which is a copy of "c".
"arg" was created as part of the f(c) expression (IMHO).

Cheers,
Andre

Oct 19 '05 #7
"in*****@gmail. com" wrote:

IMHO the temporary object (arg) is created as part of the cout <<
f(c)... expression. Thus it exists until the end of that whole
expression (once again IMHO).


Actually I think you are right. *In this case* the whole thing
is defined.
Nevertheless IMHO it is poor programming praxis, if the validity
of a function depends on the exact details that function is used.

--
Karl Heinz Buchegger
kb******@gascad .at
Oct 19 '05 #8
in*****@gmail.c om wrote:
Greg wrote:
const test & f( test arg )
{
test l("local");
return arg;
}


The f() routine returns a reference to a function parameter whose
lifetime ends at function exit. Therefore I believe that the behavior
of your program is undefined.


Actually, I do think the behaviour is defined. My original question was
how to better define why it is legal - i.e. where it is mentionend in
the standard.

Victor pointed me to item 12.2 in the C++ Standard. I believe
paragraphs 2 and onward explain it (too long to reproduce here).

Given the example code (para. 2):
X f(X); // X is a class
...
X a(1);
a=f(a);

The standard writes:
"...the expression a=f(a) requires a temporary for either the
argument 'a' or the result of f(a) to avoid undesired aliasing of 'a'."

B.Stroustrup writes (similar wording to the standard para. 3) in "The
C++ Programming Language", section 10.4.10:
"Unless bound to a reference or used to initialize a named object, a
temporary object is destroyed at the end of the full expression in
which it was created."

IMHO the temporary object (arg) is created as part of the cout <<
f(c)... expression. Thus it exists until the end of that whole
expression (once again IMHO).

Is this not correct?

Cheers,
Andre


You are correct abut the temporary. But the program's behavior is still
undefined.

The problem is not the lifetime of the temporary reference that the
function returns, but the lifetime of the object that it is bound to.
It is bound to a function parameter passed by value - not by reference.
Because it is a value parameter, its lifetime is certain to end before
the function exits. So the return value used in the calling routine is
in fact in scope, but the variable it is bound to has been destroyed.
Accessing a reference to a deallocated variable is undefined behavior.

Greg

Oct 19 '05 #9

Greg wrote:
in*****@gmail.c om wrote:
Greg wrote:
.... The problem is not the lifetime of the temporary reference that the
function returns, but the lifetime of the object that it is bound to.
It is bound to a function parameter passed by value - not by reference.
Because it is a value parameter, its lifetime is certain to end before
the function exits. So the return value used in the calling routine is
in fact in scope, but the variable it is bound to has been destroyed.
Accessing a reference to a deallocated variable is undefined behavior.


I think that the bottom line of our disagreement is the question
whether a pass-by-value function argument has function scope or not. I
do not believe it does.

The function argument - especially in the case of a complex class - is
allocated (and copy constructed) BEFORE the function is entered. Thus
its lifetime is not within the function scope but bound by the complete
expression it is part of. As such, as outlined by the previous
quotations, I believe it is not destroyed before the full expression is
evaluated.

This case only really matter of course if you return a reference to the
argument like I did. But it can be illustrated similarly even with a
function that doesn't return the argument in any form:

int f1( my_class arg )
{
return 42;
}

When calling this function, a temporary my_class object is allocated
and copy constructed, and not destroyed until the full expression it
may be part of is evaluate.

E.x:
cout << f1( c ) << " is the answer." << endl;

That is how I understand and interpret the standard - I may be wrong.

Cheers,
Andre

Oct 19 '05 #10

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

Similar topics

3
14953
by: domeceo | last post by:
can anyone tell me why I cannot pass values in a setTimeout function whenever I use this function it says "menu is undefined" after th alert. function imgOff(menu, num) { if (document.images) { document.images.src = eval("mt" +menu+ ".src") } alert("imgOff_hidemenu"); hideMenu=setTimeout('Hide(menu,num)',500);
2
7681
by: laredotornado | last post by:
Hello, I am looking for a cross-browser way (Firefox 1+, IE 5.5+) to have my Javascript function execute from the BODY's "onload" method, but if there is already an onload method defined, I would like mine to run immediately after it. So in the code below, what JS would i need to add to my "myfile.inc" page so that I could guarantee this behavior? <!-- main page --> <html> <head> <script type="text/javascript">
17
3605
by: Charles Sullivan | last post by:
The library function 'qsort' is declared thus: void qsort(void *base, size_t nmemb, size_t size, int(*compar)(const void *, const void *)); If in my code I write: int cmp_fcn(...); int (*fcmp)() = &cmp_fcn; qsort(..., fcmp); then everything works. But if instead I code qsort as:
4
1835
by: Nicholas Beenham | last post by:
Hi all, Is there a way to set the lifespan of a thread. I am trying to start a process that may or may not have an outcome and want to finish it after a certain length of time finished or not. So I have Thread t = new Thread(new ThreadStart(targetMethod));
4
1958
by: abCSharp | last post by:
I understand that static variables have app-domain scope. Till the app-domain is in memory, the static variable will be in memory. When are the app-domains unloaded is the question. I have read somewhere in this forum that statics live till the asp.net process is recycled. Please clarify if someone can. Thanx! "David Jessee" wrote: > I'd be VERY careful about using a shared page member for state management. > its true that there is...
20
2066
by: asdf | last post by:
True or false ?
28
4340
by: Larax | last post by:
Best explanation of my question will be an example, look below at this simple function: function SetEventHandler(element) { // some operations on element element.onclick = function(event) {
4
1956
by: =?Utf-8?B?RGF2aWQgVGhpZWxlbg==?= | last post by:
Hi; When a Page object - the code-behind of an aspx page is created - what is the lifespan of that created object? Is it tied to the session, the request/response, or is it in a poll and reused for the next request/response to that page from any session? -- thanks - dave david_at_windward_dot_net
3
2070
by: David Cox | last post by:
I found some details on a musical festival, made my plans, and only found out by chance that the site was two years out of date. Is there some HTML way of setting a lifespan on a webpage on creation so that, should the creator neglect to remove it, browsers will not render it? If not should such a mechanism exist? Perhaps with page expired message? David F. Cox
0
9671
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...
1
10161
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
10000
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
9035
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7538
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
6777
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
5436
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...
2
3720
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2919
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.