Lifetime of a temporary bound to a reference

I'm not sure what the standard says about a case like this (mainly per
12.2/5):

class B {};
class D1: public B {};
class D2: public B {};

void foo( bool r )
{
	B const& a = ( r ? D1() : D2() );
	// Does the temporary live here?
}

itaj

-- 
      [ See http://www.gotw.ca/resources/clcm.htm for info about ]
      [ comp.lang.c++.moderated.    First time posters: Do this! ]

0
itaj
6/27/2010 8:27:25 AM
comp.lang.c++.moderated 10705 articles. 11 followers. allnor (8507) is leader. Post Follow

5 Replies
216 Views

Similar Articles

[PageSpeed] 42
itaj sherman wrote:

> I'm not sure what the standard says about a case like this (mainly per
> 12.2/5):
> 
> class B {};
> class D1: public B {};
> class D2: public B {};
> 
> void foo( bool r )
> {
> B const& a = ( r ? D1() : D2() );
> // Does the temporary live here?
> }
> 

First of all, that code isn't valid. Let's change it to

    B const& a = ( r ? B() : D2() );

"Temporary" is a property of objects and strictly according to standards the
lifetime of it should be lengthened. But the aim of the Standard is that
only "direct" references to temporaries are lifetime-extended. What such a
"direct" reference is, however, isn't specified by the Standard as far as i
know.

In your example, even tho the result is an rvalue that definitely refers to
a temporary, that rvalue refers *either* a temporary coming from the left
*or* from the right side. Thus there is no direct reference anymore, in some
sense.

The issue around ?: and temporaries is subject of http://www.open-
std.org/jtc1/sc22/wg21/docs/cwg_active.html#462 . The direction that #462
drives toward is making "temporary" a property of expressions, instead of a
property of objects, without explicitly mentioning it in that issue report.
That issue report is the only place i know that would attribute it to
expressions explicitly. Many places in the Standard already seem to assume
that, while the text in the Standard is clear that it is a property of
objects.

To me it seems the following solves these questions too, with much less
overhead:

- Say that lifetime extension rules only apply to temporaries that haven't
been bound to references or to the implicit object parameter yet.

This is sort of what the RVO rules do, saying that they only apply to
temporaries that haven't yet been bound to references. I suspect here is a
reason they haven't done this way, but i can't think of a reason.

This would allow the above conditional-expression be lifetime extended too.
It still disallows extending lifetime of a "*this" refering to a temporary
object and other such things, which is the aim of the Standard. It would
keep the term "temporary" to strictly name a property of objects.

-- 
      [ See http://www.gotw.ca/resources/clcm.htm for info about ]
      [ comp.lang.c++.moderated.    First time posters: Do this! ]

0
Johannes
6/28/2010 1:37:54 PM
itaj sherman wrote:

> I'm not sure what the standard says about a case like this (mainly per
> 12.2/5):
> 
> class B {};
> class D1: public B {};
> class D2: public B {};
> 
> void foo( bool r )
> {
> B const& a = ( r ? D1() : D2() );
> // Does the temporary live here?
> }
> 

I'm sorry to annoy you again, but i've just noticed that the issue report
link i gave was discussing the comma operator instead of the conditional
operator (omg, epic fail).  It turns out from links in that issue report
that the issue with the conditional operator has been fixed in C++0x by
http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#446 . It
provides the "direct reference" i talked about.

Looking at it again, i found an interesting similarity with bit-fields: An
object can be a bit-field, but an expression can be a bit-field likewise.
Like, it's said "the result is of that type and value category and it is a
bit-field if ..." at 5.16/4 in the FCD. If it would omit the addendum, the
expression would potentially refer to a bit-field, but won't be a bit-field
itself. This seems to be exactly like the situation with temporaries. The
lifetime-lengthening subsection refers to the expression property, thus it
doesn't care about lvalues that refer to temporaries, because those lvalues
won't have the "temporary" property be true. But now, i'm just more confused
how these things fit together, really :(

-- 
      [ See http://www.gotw.ca/resources/clcm.htm for info about ]
      [ comp.lang.c++.moderated.    First time posters: Do this! ]

0
Johannes
6/28/2010 1:39:00 PM
On Jun 27, 5:27 pm, itaj sherman <itajsher...@gmail.com> wrote:
> I'm not sure what the standard says about a case like this (mainly per
> 12.2/5):
>
> class B {};
> class D1: public B {};
> class D2: public B {};
>
> void foo( bool r )
> {
>         B const& a = ( r ? D1() : D2() );
>         // Does the temporary live here?
>
> }

AFAIK, it does. E.g. ScopeGuard of Petru/Alexandrescu uses that
language feature.

Goran.


-- 
      [ See http://www.gotw.ca/resources/clcm.htm for info about ]
      [ comp.lang.c++.moderated.    First time posters: Do this! ]

0
Goran
6/28/2010 1:39:59 PM
On 27 June, 17:27, itaj sherman <itajsher...@gmail.com> wrote:
> I'm not sure what the standard says about a case like this (mainly per
> 12.2/5):
>
> class B {};
> class D1: public B {};
> class D2: public B {};
>
> void foo( bool r )
> {
>         B const& a = ( r ? D1() : D2() );
>         // Does the temporary live here?
>
> }


Hi, the temporary in such a case lives as long as the reference does.
Have a look at this article:
http://herbsutter.com/2008/01/01/gotw-88-a-candidate-for-the-most-important-const/

Your example however will not compile, because operator ?: is not that
clever to deduce that you mean the common base type. You have to cast
at least one of the operands explicitly:

  B const& a =  r ? static_cast<B&>( D1() ): D2();

Regards,
&rzej

-- 
      [ See http://www.gotw.ca/resources/clcm.htm for info about ]
      [ comp.lang.c++.moderated.    First time posters: Do this! ]

0
restor
6/28/2010 1:52:01 PM
On Jun 27, 6:27 pm, itaj sherman <itajsher...@gmail.com> wrote:
> I'm not sure what the standard says about a case like this (mainly per
> 12.2/5):
> 
> class B {};
> class D1: public B {};
> class D2: public B {};
> 
> void foo( bool r )
> {
>         B const& a = ( r ? D1() : D2() );

//original code doesn't compile, it should have been:
B const& a = ( r ? static_cast<B const&>(D1()) : static_cast<B
const&>(D2()) );
//or:
B const& a = ( r ? B() : D2 );

>        // Does the temporary live here?

//would that change the answer?


> 
> }
> 
> itaj
> 

itaj


-- 
      [ See http://www.gotw.ca/resources/clcm.htm for info about ]
      [ comp.lang.c++.moderated.    First time posters: Do this! ]

0
itaj
6/28/2010 6:29:16 PM
Reply:
Similar Artilces:

Object reference question
I have an easy question for you all. I need to get a reference to a JTable that is in a JScrollPane which is in a tab of a JTabbedPane. I need this reference so I can pass it along to other methods for further processing. I can get the reference to the selected tab's JScrollPane doing Component comp = jTabbedPane.getComponentAt(jTabbedPane.getSelectedIndex()); Not sure how to get the reference to the JTable. Thanks in Advance... IchBin, Pocono Lake, Pa, USA http://weconsultants.servebeer.com/JHackerAppManager _________________________________________________________________________...

Lifetime of a Battery
I have a question and "old adage" that I would like comment on. 1. What is the lifetime of a battery? 2. Is there any truth to the "old adage" that you should periodically run your battery down to extend its lifetime. I think this comes from a comment I heard that it is not good to always run you laptop on wall power; this actually decreases the lifetime of a battery. I have a Dell Inspiron (550 mHZ; over four years old) that I almost never ran on the battery. I recently tried to use the battery and it would not charge up. Phil McClean 1. The life of a battery is...

Re: Passing by reference #2
Thanks Mark for correcting that code. My asprine finally started to kick in this morning to end this splitting headache... Toby Dunn From: "Terjeson, Mark (IM&R)" <Mterjeson@RUSSELL.COM> Reply-To: "Terjeson, Mark (IM&R)" <Mterjeson@RUSSELL.COM> To: SAS-L@LISTSERV.UGA.EDU Subject: Re: Passing by reference Date: Tue, 13 Dec 2005 07:24:26 -0800 Hi, Toby is right, intermixing macro and datastep code is full of timing issues, and CALL EXECUTE() is the elegant approach. A couple slight punctuation tweaks and you're off an running. Removing the...

Offline Temporary Tablespace
I have a continuing problem with the temporary tablespace for a DB2 database. The tablespace goes offline. I created a new temporary tablespace and once it was online I removed the tablespace that was offline. Within a few minutes the new tablespace went offline as well. The following information was found in the db2diag.log 2003-06-25-07.47.18.272000 Instance:DB2 Node:000 PID:1804(db2syscs.exe) TID:3116 Appid:C0A80486.9204.030625124711 buffer_pool_services sqlbStartUsingFile Probe:805 Database:CPPARMS DIA3501C Access denied for resource "", operating system ret...

Importing Images To LaTeX, with a no Bounding Box error!?
I have been trying to solve this for quite awhile, and am baffled, as I cannot work out why I get this error. I use LEd, and I need to import a .eps file into the my document. I created the eps file by making the thing I want on Microsoft Word, then convert it to postscript via the Generic PostScript Print. I then manipulate the ending of .ps to .eps; or I convert it using GSview. Anyway, I have this .eps file, I check it in notepad it seems to have a bounding box, according to the settings (I even changed these to make it closer to the image but still did not work). So I put this eps file in...

Declared Temporary Table in Cobol
Hi, Having checked out a declared (rather than created) temporary table successfully in SPUFI, I have hit a problem in running the same SQL in the cobol prog I am ameding to use it. I have: existing SQL declare temporary table insert in temporary table select from temporary table only select from temporary table joined to others The program fails at the last step of the above(-306?), saying it has never heard of 'a.column' where 'a' refers to my temporary table. The precompiler returns warnings whereever the temporary table is referenced. I understand it mark...

Taking a reference to a temporary: why illegal
Hello, Is there a good reason that the code below is illegal? a) No. It's an artifact of some other situation and you get to bear the pain by having your cute one-liner rendered illegal b) Yes. That code could cause a segfault on hardware due to assumptions that the compiler makes about things that are too complicated for you to understand. c) Well if you don't like it why don't you create your own programming language you lazy leech. d) This is not the correct forum for this question, now scram before I have to get snooty. e) [your answer here] I'm ...

array reference 30509
Hi, I have a function returning a list. I want to pass this list to another function, by reference. this works my @list = GetList(); my $listref = \@list; ReadList($listref); but I wish to know if it's possible to do in a single command, something like ReadList(\@{GetList()}); unfortunately, it doesn't work. anyone? tamiry wrote: > Hi, > I have a function returning a list. I want to pass this list > to another function, by reference. > > this works > my @list = GetList(); > my $listref = \@list; > ReadList($listref); > > but I wish to know if it...

Problem with passing dynamic arrays by reference
Hi! Sorry for the weird topic, I don't know how to describe it better... I have a little problem here I can't wrap my mind around. If I do: ------------------------------------- #define DWORD unsigned long #include <stdio.h> #include <malloc.h> int main(int argc, char* argv[]) { DWORD *arr; int i; arr = malloc(sizeof(DWORD)); arr[0] = 1; arr = realloc(arr,2*sizeof(DWORD)); arr[1] = 2; for(i=0;i<=1;i++) { printf("%d\n",arr[i]); } } ------------------------------------- This works just fine, as expected. But when I try to do the allocation and as...

functions and temporary tables
hi, i'm writing some plpgsql functions which use a temporary table, and i've read the FAQ and am using EXECUTE to create and insert into my table to avoid errors caused by postgres caching the query plan. however, i can't work out how to get the data back out of my temporary table, as i don't think i can get the results of a select performed using EXECUTE? if i just do the select directly, once the temporary table has been recreated, the select fails with the error "relation with OID xxxxx does not exist". Can anyone suggest how I can void this and get data ...

meaning of frame of reference
Hi, what does it mean the tag FrameOfRefernceUID (20,52) and how is tipically generated the uid? thanx tommy sanx "Ing. Tommaso Sansoni" <tsansoni1@tin.it> wrote in message news:<2NHdc.52448$rM4.2075325@news4.tin.it>... > Hi, > what does it mean the tag FrameOfRefernceUID (20,52) and how is > tipically generated the uid? > > thanx > tommy sanx The UID is generated the same as any other DICOM UID. You can find a detailed write up on algorithms for generating UIDs in DICOM part 5, section 9 which you can find here ftp://med...

Bad spacing in references
Dear group, In article document class, I am using \bibliographystyle{prsty} \bibliography{biblio} to generate the list of references (with BibTeX). However, although the spacing is correct in Phys. Rev. journals which use this prsty style, in article's document class there is a big spacing between two references, something like [1] this first ref... [2] this second one... Instead of [1] this first ref... [2] this second one... etc. How could this be fixed? Best, Fabrice. In article <4208fa99$0$27055$626a14ce@news.free.fr>, "F.P. Laussy" <laussy@shield-spam....

Apple IIc Technical Reference 2nd edition
Does anyone have an original copy of the Apple IIc Technical Reference 2nd edition. I am looking for a legible scan of pages 407 to 418. These are schematics for the IIc and IIc+ I have a copy of the publication from Syndicomm. Thanks Glenn "Glenn Jones" <apple2stuff@rogers.com> wrote in message news:<VOOdnUOEr8hJhwHcRVn-1A@rogers.com>... > Does anyone have an original copy of the Apple IIc Technical Reference 2nd > edition. > > I am looking for a legible scan of pages 407 to 418. These are schematics > for the IIc and IIc+ > > I have a copy ...

all in one c++ reference
i am a java programmer and it seems i have been spoiled by the documentation and the precompiled API freely availible on the web. is there anything compareble to that with c++? i cannot find any official c++ website such as java.sun.com. any help would be appreciated. Josh Sebastian wrote: > On Sat, 06 Sep 2003 01:11:19 -0700, mtfulmer wrote: > > >>i am a java programmer and it seems i have been spoiled by the >>documentation and the precompiled API freely availible on the web. is >>there anything compareble to that with c++? i cannot find any official >>c++...

Lifetime guarantee on printheads?
Is there really a lifetime guarantee on Epson printheads as it says on http://www.ssclg.com/epsone.shtml ? > Is there really a lifetime guarantee on Epson printheads as it says on > http://www.ssclg.com/epsone.shtml Maybe. The trick with lifetime guarantees is that manufacturers often have a loophole which states it's the lifetime of the product, not your lifetime, and the second your product breaks, it is effectively at the end of its lifetime. :-) I'm sorry but something apparently got "lost in translation". The website you are discussing i...

C++11 rvalue reference question
class O {...}; class I {...}; class E {...}; Suppose we have some function f that takes an instance of class I as input and produces an instance of class O as output (throwing an instance of class E on an error): O f(const I& i) { O result; ... // mutate result based on i if (...) throw E(...); return result; } I i = ...; O o = f(i); In C++03 many times it was recommend to write such a function as follows: void f(O& out, const I& i) { .... // mutate result based on i if (,,,) throw E(...); } I i = ...; O o; f(o,i); I suspect this is to ...

Is it possible to disable telnet login session temporary in AIX?
Hello All, I am a new to AIX and wondering if there is a way/command to disable telnet user to the system temporary. In the real world, even though I asked other users not to login to system, I still get a few pts sessions when I issue the "w" command. I found the penable and pdisable commands. Try them on my system and it's still not preventing telnet user from logging into the system. Is the kill command the only option? Thanks, Bob. "Bob Bale" <balebob@hotmail.com> wrote in message news:6385ed14.0307281908.1601ff29@posting.google.com... > Hello All, ...

How to return a reference
I know it is possible to pass a paramater explicitly by reference with an &, but doing this on a return statement seems to create a syntax error... Is it possible to return a reference? If so how? Thanks On Dec 22, 9:06=A0am, marksmith5...@jungle-monkey.com wrote: > I know it is possible to pass a paramater explicitly by reference with > an &, but doing this on a return statement seems to create a syntax > error... Is it possible to return a reference? If so how? > > Thanks php.net is your friend. http://www.php.net/manual/en/language.references.return.php On Dec 22...

Re: DIrectv Not Honoring Tivo Lifetime Service #5
On 20 Dec 2004 11:58:39 -0800, googlenospam@netcrafting.com wrote: > I cannot believe this is happening. I thought a lifetime > subscription lasted the lifetime of the Tivo unit? This is not the > case for folks who were serviced by Pegasus. Beware if you buy a > lifetime Tivo on Ebay that was owned by a customer who got their > satellite service from Pegasus. Well, buying anything "lifetime" should always be considered a risk. What lifetime are they referring to? Yours, the satellite receiver, the company? What applies to gym memberships probably applies...

determining the bounds of a tuple returned from a database
here is my result. How do I determine the number of tuples in this array, returned from a mysql database? How do I determine the number of characters or entry in each tuple? thanks very much for your assistance, -rsr- (('Agricultural subsidies; Foreign aid',), ('Agriculture; Sustainable Agriculture - Support; Organic Agriculture; Pesticides, US, Childhood Development, Birth Defects; Toxic Chemicals',), ('Antibiotics, Animals',), ('Agricultural Subsidies, Global Trade',), ('Agricultural Subsidies',), ('Biodiversity',), ('Citizen Activism&...

How to handle a shared object reference?
Hi. I'm doing a design using Java that has two hierarchies of classes. Each hierarchy is defined by containment. So it's something like: class A contains an instance of B; class B contains an instance of C; class C contains an instance of D; class A contains an instance of E; class E contains an instance of F; class F contains an instance of G; So both hierarchies start with class A. Using this example, classes D and G (the classes at the bottom of these hierarchies) both use the same instance of another class. We'll call that class SharedClass. D creates, writes to and re...

Object lifetimes when bound to references
Hello, during a discussion on a C++ internet forum, some question came up regarding references and the lifetime of the objects they alias. I can't find any clear wording on that in the draft standard. Example 12.2 in the standard document illustrates that temporaries bound to references-to-const live as long as the reference does. But does it e.g. matter if the temporary was created in scope of a function body and has to outlive the function call? And what happens with this temporary when everything else from the stack has to be destroyed except the temporary? Is it copied to a new...

Online Dylan Reference Manual Updated #3
The online Dylan Reference Manual has been updated. I've made numerous cleanups to the XHTML, as well as the following user-visible changes: - Fixed the layout of headers and method signatures that contain "[...]" attributes summaries. Previously, long signatures could overlap the attributes tag on-screen, and when printing, Firefox placed the attributes tag below the header/signature line. - Fixed all the typography of the "Macro Call" sections that describe the syntax of the built-in macros. They were really messed up before, making them difficu...

need help-how to parse references
Hello everyone: I am a perl beginner. I am practicing to parse a list of different references. The list looks like any references followed a paper. In the list, every reference has different numbers of authors. Most references are either books or journals. I would like to separate each field, for example, the result I assume looks like: author article name journal name or book name volume#...year Alison Balter Access 2000 development 1999 I feel it is hard to find a regular expression to separate them. Does anyone advise me where I can find more inforamtion?...

Warning: constant expression violates subrange bounds
Hi everybody, On the internet I found a small unit to calculate CRC32 values, which I need for a small project. However, when I include this unit in my project, I suddenly get a lot of warnings like the following: [DCC Warning] Crc32.pas(15): W1012 Constant expression violates subrange bounds I've had a look around on the net on several forums, and they all seem to offer solutions on how to change the code, so the warning doesn't appear at all. However, I'm not inclined to change the unit (as I don't want to mess with all those declared constants), so I...