473,473 Members | 1,962 Online
Bytes | Software Development & Data Engineering Community
Create Post

Home Posts Topics Members FAQ

lifetime of temp string object

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();
std::cout << s << std::endl;
return 0;
}
As I understand the C++ standard the lifetime of the temporary string
object created on the first line of main() ends when the expression
containing it ends (unless an object is initialized as a reference to
the temporary).

If that is true, then the memory s points to is invalidated, since the
temporary string is destructed.

The project I am working on has quite a lot of the above construct, but
I could not bring myself to change all of these, unless I am quite sure
it causes undefined behavior.

Thanks,

Gabor Drasny
Aug 9 '05 #1
15 4283
Gabor Drasny wrote:
Could anyone tell me if the following code is guaranteed to work or not?
Not.
#include <string>
#include <iostream>

int main()
{
const char* s = std::string("Hello World").c_str();
This is rather unusual. Why not simply write

const char* s = "Hello World";

???
std::cout << s << std::endl;
return 0;
}
As I understand the C++ standard the lifetime of the temporary string
object created on the first line of main() ends when the expression
containing it ends (unless an object is initialized as a reference to
the temporary).
Yes.
If that is true, then the memory s points to is invalidated, since the
temporary string is destructed.
It is.
The project I am working on has quite a lot of the above construct, but
I could not bring myself to change all of these, unless I am quite sure
it causes undefined behavior.


It does.

V
Aug 9 '05 #2
* Gabor Drasny:
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();
std::cout << s << std::endl;
return 0;
}
Not guaranteed to work:

* Formally you need to also include <ostream>. ;-)

* The temporary std::string ceases to exist after the expression.

The project I am working on has quite a lot of the above construct, but
I could not bring myself to change all of these, unless I am quite sure
it causes undefined behavior.


It's UB.

But note that

int main()
{
std::string const& str = std::string( "Hello, world!" );
const char* s = std.c_str();
std::cout << s << std::endl;
}

is not UB, because that reference to const keeps the temporary, so to speak.

--
A: Because it messes up the order in which people normally read text.
Q: Why is it such a bad thing?
A: Top-posting.
Q: What is the most annoying thing on usenet and in e-mail?
Aug 9 '05 #3
Inline.

"Alf P. Steinbach" <al***@start.no> wrote in message
news:42****************@news.individual.net...
* Gabor Drasny:
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();
std::cout << s << std::endl;
return 0;
}
Not guaranteed to work:

* Formally you need to also include <ostream>. ;-)

* The temporary std::string ceases to exist after the expression.

The project I am working on has quite a lot of the above construct, but
I could not bring myself to change all of these, unless I am quite sure
it causes undefined behavior.


It's UB.

But note that

int main()
{
std::string const& str = std::string( "Hello, world!" );
const char* s = std.c_str();
std::cout << s << std::endl;
}

is not UB, because that reference to const keeps the temporary, so to

speak.
It might do that in Java or some other language with a GC but not in C++,
this is still UB.
--
A: Because it messes up the order in which people normally read text.
Q: Why is it such a bad thing?
A: Top-posting.
Q: What is the most annoying thing on usenet and in e-mail?

Aug 9 '05 #4
"Alf P. Steinbach" <al***@start.no> wrote in message
news:42****************@news.individual.net...

int main()
{
std::string const& str = std::string( "Hello, world!" );
const char* s = std.c_str();


Typo! Make that:

const char* s = str.c_str();
-Mike
Aug 9 '05 #5
* Adrian:
Inline.
What do you mean by that?
* Adrian: "Alf P. Steinbach" <al***@start.no> wrote in message
news:42****************@news.individual.net...
* Gabor Drasny:
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();
std::cout << s << std::endl;
return 0;
}


Not guaranteed to work:

* Formally you need to also include <ostream>. ;-)

* The temporary std::string ceases to exist after the expression.

The project I am working on has quite a lot of the above construct, but
I could not bring myself to change all of these, unless I am quite sure
it causes undefined behavior.


It's UB.

But note that

int main()
{
std::string const& str = std::string( "Hello, world!" );
const char* s = std.c_str();
std::cout << s << std::endl;
}

is not UB, because that reference to const keeps the temporary, so to
speak.


It might do that in Java or some other language with a GC but not in C++,
this is still UB.


You're wrong.

--
A: Because it messes up the order in which people normally read text.
Q: Why is it such a bad thing?
A: Top-posting.
Q: What is the most annoying thing on usenet and in e-mail?
Aug 9 '05 #6
"Adrian" <ba******@xoasis.com> wrote in message
news:42********@news.microsoft.com...
Inline.

"Alf P. Steinbach" <al***@start.no> wrote in message
news:42****************@news.individual.net...
It's UB.

But note that

int main()
{
std::string const& str = std::string( "Hello, world!" );
const char* s = std.c_str();
std::cout << s << std::endl;
}

is not UB, because that reference to const keeps the temporary, so to

speak.


It might do that in Java or some other language with a GC but not in C++,
this is still UB.


C&V please

-Mike
Aug 9 '05 #7
* Mike Wahler:
"Alf P. Steinbach" <al***@start.no> wrote in message
news:42****************@news.individual.net...

int main()
{
std::string const& str = std::string( "Hello, world!" );
const char* s = std.c_str();


Typo! Make that:

const char* s = str.c_str();


Thanks.

--
A: Because it messes up the order in which people normally read text.
Q: Why is it such a bad thing?
A: Top-posting.
Q: What is the most annoying thing on usenet and in e-mail?
Aug 9 '05 #8
Alf P. Steinbach wrote:
[...]
But note that

int main()
{
std::string const& str = std::string( "Hello, world!" );
const char* s = std.c_str();
... str.c_str();
std::cout << s << std::endl;
}

is not UB, because that reference to const keeps the temporary, so to speak.


Yes, but why would anybody do that, when it's SO much easier to do

std::string const str("whatever");
const char* s = str.c_str();

(if the string is actually what's needed, I mean)...

:-)

V
Aug 9 '05 #9
* Victor Bazarov:
Alf P. Steinbach wrote:
[...]
But note that

int main()
{
std::string const& str = std::string( "Hello, world!" );
const char* s = std.c_str();
... str.c_str();
std::cout << s << std::endl;
}

is not UB, because that reference to const keeps the temporary, so to speak.


Yes, but why would anybody do that, when it's SO much easier to do

std::string const str("whatever");
const char* s = str.c_str();

(if the string is actually what's needed, I mean)...


I just thought I should mention it, in case the OPs example code was more
like an impression of the code in question.

:-)


--
A: Because it messes up the order in which people normally read text.
Q: Why is it such a bad thing?
A: Top-posting.
Q: What is the most annoying thing on usenet and in e-mail?
Aug 9 '05 #10
What I meant is that by declaring
std::string const& str = std::string( "Hello, world!" );
you just define an alias for the object, the object itself is still allowed
to go out of scope. I don't have the standard handy but I don't think the
compiler is required to keep the object around for the lifetime of the
reference. I think you are confusing the reference concept with the one from
grabage collected languages where a reference will indeed prevent the object
from being destroyed.

If what you're saying was true life would be sweet because we could do
things like this:

const std::string& foo()
{
return std::string("foo");
}

This looks like an efficient way to return a std::string, unfortunately it
doesn't work.

Adrian

"Alf P. Steinbach" <al***@start.no> wrote in message
news:42****************@news.individual.net...
* Adrian:
Inline.


What do you mean by that?
* Adrian:
"Alf P. Steinbach" <al***@start.no> wrote in message
news:42****************@news.individual.net...
* Gabor Drasny:
> 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();
> std::cout << s << std::endl;
> return 0;
> }

Not guaranteed to work:

* Formally you need to also include <ostream>. ;-)

* The temporary std::string ceases to exist after the expression.
> The project I am working on has quite a lot of the above construct, but > I could not bring myself to change all of these, unless I am quite sure > it causes undefined behavior.

It's UB.

But note that

int main()
{
std::string const& str = std::string( "Hello, world!" );
const char* s = std.c_str();
std::cout << s << std::endl;
}

is not UB, because that reference to const keeps the temporary, so to
speak.


It might do that in Java or some other language with a GC but not in C++, this is still UB.


You're wrong.

--
A: Because it messes up the order in which people normally read text.
Q: Why is it such a bad thing?
A: Top-posting.
Q: What is the most annoying thing on usenet and in e-mail?

Aug 9 '05 #11
* Adrian:
[top-posting]
Please don't top-post in this group -- read the FAQ.
* Adrian: What I meant is that by declaring
std::string const& str = std::string( "Hello, world!" );
you just define an alias for the object, the object itself is still allowed
to go out of scope. I don't have the standard handy but I don't think the
compiler is required to keep the object around for the lifetime of the
reference.
It is; and do get yourself a copy of the standard.

If what you're saying was true life would be sweet because we could do
things like this:

const std::string& foo()
{
return std::string("foo");
}


Sorry, that's incorrect.

--
A: Because it messes up the order in which people normally read text.
Q: Why is it such a bad thing?
A: Top-posting.
Q: What is the most annoying thing on usenet and in e-mail?
Aug 9 '05 #12
Please don't top-post in this group -- read the FAQ. Sorry.


* Adrian:
What I meant is that by declaring
std::string const& str = std::string( "Hello, world!" );
you just define an alias for the object, the object itself is still allowed to go out of scope. I don't have the standard handy but I don't think the compiler is required to keep the object around for the lifetime of the
reference.


It is; and do get yourself a copy of the standard.


Would you mind pointing me to the actual wording that mandates this? Thanks.

Aug 9 '05 #13
* Adrian:
Please don't top-post in this group -- read the FAQ.

Sorry.


* Adrian:
What I meant is that by declaring
std::string const& str = std::string( "Hello, world!" );
you just define an alias for the object, the object itself is still allowed to go out of scope. I don't have the standard handy but I don't think the compiler is required to keep the object around for the lifetime of the
reference.


It is; and do get yourself a copy of the standard.


Would you mind pointing me to the actual wording that mandates this? Thanks.


Not at all, it's my pleasure. Navigating the standard is an art, not a
science, but an example such as this may help. To follow this example
you'll need to get hold of the standard (if you don't have it) or
alternatively the CD2, the last committee draft before the 98 standard.

The natural first place to look is in section 7, "Declarations".

However, there's seemingly nothing there, so the second natural choice is
section 8, "Declarators". And indeed there's some hinting about this in
§8.5.3 "References". But that's not the full story, and not definitive.

One might then be tempted to look in section 3 "Basic Concepts", subsection
3.7 "Storage duration", but alas, there's nothing relevant there.

And in fact, it's necessary to either be very patient and peruse long lists
of hits from the search function, or already know where what one is looking
for is (I chose the latter since it's way easier!), namely section 12
"Special member functions" -- and now I can almost hear some readers
screaming "What the heck has references to temporaries to do with special
member functions?", to which the answer is copy constructors -- subsection
12.2 "Temporary objects", and there (I won't lead you to the actual
paragraph) it is.

--
A: Because it messes up the order in which people normally read text.
Q: Why is it such a bad thing?
A: Top-posting.
Q: What is the most annoying thing on usenet and in e-mail?
Aug 10 '05 #14
Thank you guys for all the responses. I was secretly hoping that someone
would disprove my suspicion, but confirming it is useful, too.
Yes, but why would anybody do that, when it's SO much easier to do

std::string const str("whatever");
const char* s = str.c_str();

(if the string is actually what's needed, I mean)...

:-)

V


The example I sent was admittedly a little stupid for the sake of
brevity, the situation that occurs frequently in my project is more like

std::string foo(<args>);
....
const char* s = foo(<args>).c_str();

or even

const char* s = (foo(<args1>) + foo(<args2>)).c_str();
One more followup question:

I am right to assume that the following is not UB:

int bar(const char* s) { ... }
std::string foo(int k) { ... }
....
int n = bar(foo(k).c_str());
Thanks,
Gabor Drasny


Aug 10 '05 #15

Gabor Drasny schreef:
I am right to assume that the following is not UB:

int bar(const char* s) { ... }
std::string foo(int k) { ... }
...
int n = bar(foo(k).c_str());


Yes. The temporary returned from foo(k) is destroyed
after n is assigned to. That means the const char* is
also valid until that time. bar() obviously was called
and has returned before the assignment to n

HTH,
Michiel Salters.

Aug 10 '05 #16

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

Similar topics

1
by: Thomas | last post by:
It looks like the String.replace doesn't work in IE6.1. Anyone else has the same problem. I am using newest service package of IE and Win2K. Thanks
8
by: pt | last post by:
Hallo, i wonder how it is going to be of this code below regarding of the return of temporary object. Prototypes: =========== bool Activation(TCHAR *c); std::basic_string<TCHAR> GetFile();
6
by: Christopher Benson-Manica | last post by:
<html> <head> <script> var s=String( 'foo' ); alert( s ); s.bar='bar'; alert( s.bar ); </script></head></html> Why does the second alert produce 'undefined'? Are string objects
2
by: cnickl | last post by:
I’m not sure where to post this, so I post it here. It’s more like a VC++.NET / Managed Code problem. Probably easy to fix for you guys. I want to use a String object as a parameter for a...
2
by: Mike Moore | last post by:
does anyone have an example of how to get the connection string object converted to a string variable type in order for me to call a function?
5
by: rengeek33 | last post by:
I am building a SQL statement for Oracle and need one part of it to read: , myvar = null, myvar2 = "1", myvar3 = "0", myvar4 = null, etc. I am constructing this string using the String...
10
by: lovecreatesbea... | last post by:
Is it correct and safe to compare a string object with "", a pair of quotation marks quoted empty string?If the string object: s = ""; does s contain a single '\'? Is it better to use...
1
by: OccasionalFlyer | last post by:
I'm trying to overcome limitations in a function by passing a string object rather than a string primitive. The code to set the string object's attributes, however, seems to have no effect: var...
8
by: David Lazos | last post by:
Hi All, I use Contains method of String object to determine if a string variable has another string, like that. *************************** ipAddress.Contains("127.0.0")...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
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,...
0
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,...
0
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...
1
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...
0
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,...
1
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...
0
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...
0
muto222
php
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.