473,748 Members | 2,161 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

lifetime of temporary object from function return & optimization

pt
Hallo,

i wonder how it is going to be of this code below regarding of the
return of temporary object.

Prototypes:
===========

bool Activation(TCHA R *c);
std::basic_stri ng<TCHAR> GetFile();

Func Call:
==========

Activation((TCH AR *) myObj.GetFile() .c_str());
Summary of the Question:
=============== =========
It works fine under EVC4 & MSVC6. However, I dont know if it is
portable to g++
or other compiler.

- Is there any answer to the lifetime of temporary object for
all compilers? Does it also work fine under other compilers?

- In cosidering of effiency of the code. Is there any better solution
to just create a temporary obj like this ?

TCHAR* temp = myObj.GetFile() .c_str();
Activation(temp );

- What is the lifetime of the return value from myObj.GetFile() .c_str()
before Activation(..) is called?
Thank you very much for any suggestion.

regards,
pattreeya
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.m oderated. First time posters: Do this! ]

Jul 23 '05 #1
8 2940
pt wrote:
i wonder how it is going to be of this code below regarding of the
return of temporary object.

Prototypes:
===========

bool Activation(TCHA R *c);
std::basic_stri ng<TCHAR> GetFile();

Func Call:
==========

Activation((TCH AR *) myObj.GetFile() .c_str());
This is a VERY BAD IDEA(tm). "c_str()" returns a pointer to a _const_
TCHAR, casting away constness like this is utterly dangerous.
Summary of the Question:
=============== =========
It works fine under EVC4 & MSVC6.
"Works" is a very subjective statement, isn't it?
However, I dont know if it is
portable to g++
or other compiler.
It looks portable to me, but since I don't know what 'Activation' does
to the pointer passed to it, there is no way to tell if there are any
ill effects (like undefined behaviour).
- Is there any answer to the lifetime of temporary object for
all compilers? Does it also work fine under other compilers?
A temporary is destroyed as the last step of evaluating the full
expression during evaluation of which the temporary was created. In
your case, since 'GetFile' returns an object, and that function call
is a sub-expression of an expression used to initialise the argument
of the 'Activation' function call, the temporary should survive until
'Activation' returns.

Compilers are many, some of them implement the Standard requirements
closer to the ideal than others. The lifetime of a temporary is one
of the issues that most compilers implement correctly, AFAICT.
- In cosidering of effiency of the code. Is there any better solution
to just create a temporary obj like this ?

TCHAR* temp = myObj.GetFile() .c_str();
That should not compile. 'c_str()' returns 'TCHAR const*' and you are
not allowed to convert it to 'TCHAR*' without a const_cast. And I urge
you not to, anyway.
Activation(temp );
No, this is definitely NOT going to work. 'temp' is a dangling pointer.
The temporary returned by 'GetFile' will be disposed of at the end of
initialising 'temp', which will *immediately* make it invalid.
- What is the lifetime of the return value from
myObj.GetFile() .c_str() before Activation(..) is called?


'c_str()' does not create a separate temporary to speak of. It does
however, create a pointer to the data in the other temporary, the
'basic_string<T CHAR>' object. How it does that is implemenation-
defined. The pointer remains valid until the next call to a non-const
member function for the same object (destructor is included).

V
Jul 23 '05 #2
Victor Bazarov wrote:
pt wrote:
i wonder how it is going to be of this code below regarding of the
return of temporary object.

[snip]

V


Ok, I give up.

What is a "TCHAR"?

Is code using "TCHAR" platform-portable?

Larry
Jul 23 '05 #3
Larry I Smith wrote:
Victor Bazarov wrote:
pt wrote:
i wonder how it is going to be of this code below regarding of the
return of temporary object.

[snip]

V

Ok, I give up.

What is a "TCHAR"?

Is code using "TCHAR" platform-portable?

Larry


It is a preprocessor macro defined in the Win32 API headers (i.e.,
non-standard, non-portable) that evalutes to either char or wchar
depending on whether UNICODE is defined. Nearly all of the Win32 API
functions that take strings as parameters are actually preprocessor
macros that evaluate to a FunctionNameA or FunctionNameW version, which
take char or wchar parameters, respectively.
Jul 23 '05 #4
Larry I Smith wrote:
Victor Bazarov wrote:
pt wrote:
i wonder how it is going to be of this code below regarding of the
return of temporary object.

[snip]

V


Ok, I give up.

What is a "TCHAR"?


It matters not to the question at hand.
Is code using "TCHAR" platform-portable?


As much as you want to make it. I presume somewhere in the OP's code
there is a line like

typedef wchar_t TCHAR;
or
typedef char TCHAR;

depending on some other circumstances (macros/OS settings/whatever).

V
Jul 23 '05 #5
Victor Bazarov wrote:
Larry I Smith wrote:
Victor Bazarov wrote:
pt wrote:
i wonder how it is going to be of this code below regarding of the
return of temporary object.

[snip]
V

Ok, I give up.

What is a "TCHAR"?


It matters not to the question at hand.
Is code using "TCHAR" platform-portable?


As much as you want to make it. I presume somewhere in the OP's code
there is a line like

typedef wchar_t TCHAR;
or
typedef char TCHAR;

depending on some other circumstances (macros/OS settings/whatever).

V


Ok, Alan answered it in his post - It's WIN32 API specific.

So, code using TCHAR is not portable.

Thanks Alan.

Regards,
Larry
Jul 23 '05 #6
pt
Thanks a lot for all of the comments.

in the header file,typedef char TCHAR; so it should be portable ...

Well, regarding the temporary object, can we say that its lifetime of
return of GetFile() is existing until the end of call of
Activation(..), so to say at the end of statement?

Jul 23 '05 #7
Hi,
The return value of std::basic_stri ng<TCHAR>::c_st r() is valid until
you call non-constant member function of this object.
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.m oderated. First time posters: Do this! ]

Jul 23 '05 #8
A temporary object lives till the end of whole expression.
Thus,
Activation( myObj.GetFile() .c_str() );
is correct, while
char* temp = myObj.GetFile() .c_str();
will be invalidated immediately after ';' and should not be used in
Activation(temp );

By the way,

If you have to cast to (TCHAR*) due to removing constness, please
verify that you don't modify the paramenter string in Activation(). If
no, you'd better declare it as
bool Activation(cons t TCHAR *c);
or (same as above)
bool Activation(LPCT STR c);

Also note that, if TCHAR != char (being compiled for Unicode), c-style
casting from const char* -> const TCHAR* is meaningless and harmful.
You should use
either basic_string<TC HAR>
or convert types with special purpose macros - A2T (see
http://msdn.microsoft.com/library/en...ion_Macros.asp
for details)
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.m oderated. First time posters: Do this! ]

Jul 23 '05 #9

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

Similar topics

6
3680
by: Jason Heyes | last post by:
I am interested in the lifetime of a function argument in two cases. They are: 1. void foo(Bar bar); 2. void foo(const Bar &bar); In each case I call foo like so: foo(Bar());
15
4339
by: Gabor Drasny | last post by:
Hi all, Could anyone tell me if the following code is guaranteed to work or not? #include <string> #include <iostream> int main() { const char* s = std::string("Hello World").c_str();
3
1148
by: Bob Altman | last post by:
Hi all, I have a basic question regarding holding references to objects in unmanaged C++. Suppose my unmanaged C++ class has a method that accepts a reference to an object as an argument, and stores the object reference in a stack object, and another method that uses the stored objects in the stack object, like this: void MyClass::AcceptString(const string& myArg) { m_myStack.push(myArg); // declared as stack<string> m_myStack
14
4380
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;
17
2096
by: Klaas Vantournhout | last post by:
Hi all, I was wondering if it is possible if you can check in a function if one of the arguments is temporary. What I mean is the following. A is a class, foo is a function returning a class and bar is a function using A is an argument returning something else class A;
3
2340
by: nagashre | last post by:
class A { public: A():a(0), b(0){} handleMyMsg( char* aa, char*bb); private: processMessage();
3
1565
by: mario semo | last post by:
Hello, What does the C++ Norm says about the lifetime of compiler generated temporary variables? #include <stdio.h> class BaseRef { //--------------------------------------------------------------------------
6
2696
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
1481
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
8822
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
9359
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
9310
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
9236
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
8235
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...
0
6072
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
4592
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
2774
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2206
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.