473,699 Members | 2,834 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

lifetime of tempory generated variables

Hello,

What does the C++ Norm says about the lifetime of compiler generated
temporary variables?

#include <stdio.h>

class BaseRef
{
//--------------------------------------------------------------------------
public:
//--------------------------------------------------------------------------

BaseRef()
{
printf("ctor BaseRef %p\n",this);
}

virtual ~BaseRef()
{
printf("dtor BaseRef %p\n",this);
}

void *qPtr()
{
return 0;
}
};

class Server
{
//--------------------------------------------------------------------------
public:
//--------------------------------------------------------------------------

Server()
{
}

virtual ~Server()
{
}

BaseRef queryBaseRef()
{
return BaseRef();
}

};

int main(int argc,char *argv[])
{
Server lServer;

printf("start\n ");
{
// generates a temporary baseRef instance.
void * lPtr = lServer.queryBa seRef().qPtr();
printf("before }\n");
}
printf("after }\n");
printf("done\n" );

return 0;
}
Here is the output of 2 different compilers:

VC9
start
ctor BaseRef 0012FF6C
dtor BaseRef 0012FF6C
before }
after }
done

VACPP
start
ctor BaseRef 12FF88
before }
dtor BaseRef 12FF88
after }
done

regards,

mario semo

Jun 27 '08 #1
3 1563
On May 14, 7:56 pm, "mario semo" <mario_s...@hot mail.comwrote:
Hello,

What does the C++ Norm says about the lifetime of compiler generated
temporary variables?

#include <stdio.h>

class BaseRef
{
//--------------------------------------------------------------------------
public:
//--------------------------------------------------------------------------

BaseRef()
{
printf("ctor BaseRef %p\n",this);
}

virtual ~BaseRef()
{
printf("dtor BaseRef %p\n",this);
}

void *qPtr()
{
return 0;
}

};

class Server
{
//--------------------------------------------------------------------------
public:
//--------------------------------------------------------------------------

Server()
{
}

virtual ~Server()
{
}

BaseRef queryBaseRef()
{
return BaseRef();
}

};

int main(int argc,char *argv[])
{
Server lServer;

printf("start\n ");
{
// generates a temporary baseRef instance.
void * lPtr = lServer.queryBa seRef().qPtr();
printf("before }\n");
}
printf("after }\n");
printf("done\n" );

return 0;

}

Here is the output of 2 different compilers:

VC9
start
ctor BaseRef 0012FF6C
dtor BaseRef 0012FF6C
before }
after }
done

VACPP
start
ctor BaseRef 12FF88
before }
dtor BaseRef 12FF88
after }
done

regards,

mario semo
The code generated by VC9 is more valid because it is guaranteed that
the lifetimes of the temporaries returned by value are valid till the
execution of the containing statement. So the temporary returned by
queryBaseRef is valid untill the qPtr() is evaluated. But the way the
code is generated by the compilers varies. GCC provides similar
results like VC9.
Jun 27 '08 #2
mario semo schrieb:
What does the C++ Norm says about the lifetime of compiler generated
temporary variables?
Until the next statement.
// generates a temporary baseRef instance.
void * lPtr = lServer.queryBa seRef().qPtr();
lPtr is now a dangling reference and must mot be dereferenced anymore..
printf("before }\n");
}
printf("after }\n");
Here is the output of 2 different compilers:

VC9
start
ctor BaseRef 0012FF6C
dtor BaseRef 0012FF6C
before }
after }
done
This is standard conform.
VACPP
start
ctor BaseRef 12FF88
before }
dtor BaseRef 12FF88
after }
done
Here I am unsure.
As far as I know this is wrong, bcause the object must be destroyed
before the next statement. But maybe it /can/ be destroyed before the
next statement. Anyway it is undefined behaviour to rely in the object
existence after the statement has finished.
Maybe the automatic inliner understood your implicit dependency.

But you may explicitly extend the lifetime of temporaries creating a
const reference.

const BaseRef& tmp = lServer.queryBa seRef();

Now the temporary is valid until the end of the block. No copy is made.
Marcel
Jun 27 '08 #3
On May 14, 11:18 pm, Marcel Müller <news.5.ma...@s pamgourmet.com>
wrote:
mario semo schrieb:
What does the C++ Norm says about the lifetime of compiler
generated temporary variables?
Until the next statement.
Until the end of the full expression in which they were
generated, with a few exceptions. Thus, for example, in:

if ( generateATempor ary ) ...

the temporary does not last until the end of the if
statement---only until the end of the full expression in the
condition.

All of the exceptions extend the lifetime in some way, so you're
guaranteed at least until the end of the full expression in
every case. The most important extention is in an
initialization expression---the lifetime is extended until the
object is fully initialized, e.g.:

MyClass object( generateATempor ary ) ;

The full expression is just "generateATempo rary", but the
temporary is guaranteed to last until we return from the
contructor of object (which is not part of the expression, but
implicit in the fact that this is a definition of a class type).
// generates a temporary baseRef instance.
void * lPtr = lServer.queryBa seRef().qPtr();
lPtr is now a dangling reference and must mot be dereferenced
anymore..
printf("before }\n");
}
printf("after }\n");
Here is the output of 2 different compilers:
VC9
start
ctor BaseRef 0012FF6C
dtor BaseRef 0012FF6C
before }
after }
done
This is standard conform.
VACPP
start
ctor BaseRef 12FF88
before }
dtor BaseRef 12FF88
after }
done
Here I am unsure.
It's not conform. The standard says exactly when the destructor
must be called. Before the standard, however, the ARM (and
earlier language specifications) were considerably looser: the
destructor could be called anytime after the temporary was
"used" and before the next closing brace. Thus (assuming s is
std::string, or something with a similar interface), given:

char const* f( char const* ps )
{
std::cout << ps << std::endl ;
return ps ;
}

int
main()
{
std::string a( "abc" ), b( "123" ) ;
if ( 1 ) {
char const* p = f( (a + b).c_str() ) ;
// Note the temporary in the
// call to f...
std::cout << p << std::endl ;
}
}

According to the standard, the output in f is fine (since the
temporary will remain until the end of the full expression, i.e.
the return from f). With some pre-standard compilers, however
(including all CFront based compilers, which many considered the
de facto standard), this code was perfectly fine. With others
(g++, for example), both output failed, since the call to
std::string::c_ str() "used" the temporary, and it could be
immediately destructed (before the call to f).

In general, those compilers with a shorter than standard
lifetime (e.g. g++) changed very rapidly to the standard
lifetime; extending the lifetime typically wouldn't break much
code. Those which had a longer lifetime, however, tended to be
very cautious about shortening it, since the potential for
breaking code was much greater---even today, Sun CC has options
to support both lifetimes: standard, and until the next closing
brace. (I'm not sure off hand which is the default in the last
version, but at least until very, very recently, it was the
extended lifetime.)
But you may explicitly extend the lifetime of temporaries
creating a const reference.
const BaseRef& tmp = lServer.queryBa seRef();
Now the temporary is valid until the end of the block. No copy
is made.
The temporary which is actually bound to tmp has its lifetime
extended, but other temporaries in the expression don't. And
whether a copy is made or not depends on the implementation (but
the object must be copiable, although as far as I know, only g++
enforces this correctly).

--
James Kanze (GABI Software) email:ja******* **@gmail.com
Conseils en informatique orientée objet/
Beratung in objektorientier ter Datenverarbeitu ng
9 place Sémard, 78210 St.-Cyr-l'École, France, +33 (0)1 30 23 00 34
Jun 27 '08 #4

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

Similar topics

5
1780
by: Stuart MacMartin | last post by:
I have a problem with static lifetime (order of destruction of statics within different cpp files). I have a workaround that happens to work in my case. I'd like to know if this is luck or required to work. Consider: class A { ... static B m_b; static C& GetC(); };
11
1728
by: Trapulo | last post by:
I've a question about globa variables lifetime in an asp.net app. I've declared this class: Public Class Utils Private Shared _FcdDataManagement As FCD.DataManagement Public Shared ReadOnly Property FcdDataManagement() As FCD.DataManagement Get
9
20572
by: Chuck Cobb | last post by:
I am creating some static classes with static methods and static variables, but I have a question: What is the lifetime of static classes and static variables? Is there any risk that these items might be garbage collected if they're not used for a period of time? For example: public static class test { static Collection<string> coll;
14
4378
by: Frederick Gotham | last post by:
There is a common misconception, (one which I myself also held at one point), that a const reference can "extend the lifetime of a temporary". Examples such as the following are given: Snippet (1) ----------- #include <string> using std::string;
9
1984
by: David | last post by:
With a non-server app there is one instance of the program running and one user 'using' it at a time. With this scenario I'm pretty comfortable with variable scope and lifetime. With a server app there is one instance of the program running but several simultaneous clients connecting to and 'using' it. When I think about this I'm wondering what this may add to what needs to be considered for scope and lifetime... is a scenario created where...
4
4027
neo008
by: neo008 | last post by:
Hi all, Finally gave up and putting it here. I am new to visual basic stucked up with an error- Run time errors.'-2147217887 (8004021)': Multiple-step operation generated errors. check each status value. Error comes at ADODC.RECORDSET.UPDATE command.
3
2339
by: nagashre | last post by:
class A { public: A():a(0), b(0){} handleMyMsg( char* aa, char*bb); private: processMessage();
6
2695
by: better_cs_now | last post by:
Hello all, class Foo {/* Details don't matter */}; class Bar { public: Bar(): m_Foo(/* Construct a Foo however it wants to be constructed */); const Foo &GetFoo() const { return m_Foo; } private:
5
1478
by: Juha Nieminen | last post by:
Let's assume we have a class like this: //--------------------------------------------------------- #include <iostream> class MyClass { public: MyClass() { std::cout << "constructor\n"; } ~MyClass() { std::cout << "destructor\n"; }
0
8612
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
9171
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...
0
9032
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
8905
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
7743
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
6532
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
5869
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
4373
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...
0
4625
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?

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.