473,698 Members | 2,833 Online
Bytes | Software Development & Data Engineering Community
+ 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("He llo 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 4332
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("He llo 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("He llo 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.i ndividual.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("He llo 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.i ndividual.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.i ndividual.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("He llo 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******@xoasi s.com> wrote in message
news:42******** @news.microsoft .com...
Inline.

"Alf P. Steinbach" <al***@start.no > wrote in message
news:42******** ********@news.i ndividual.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.i ndividual.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

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

Similar topics

1
16341
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
2938
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
1385
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
1031
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 function. Here is what it should look like: String *a = "Hallo"; this->SomeClass->FormatString(a); this->label->Text = a;
2
2096
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
1913
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 object with the following code: theSQL.Append(" , myvar = " & FormatValue(MyClass.DB_CHAR1, Me.MyVar))
10
9061
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 std::string::size or std::string::empty to deal with this condition? Thank you. string s = ""; if (s == ""); if (s.size == 0); if (s.empty());
1
1416
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 msg = new String( 'WARNING: Quiting now will cancel all changes up to this point, ' + 'leaving your schedule as it was when you began this session. ' + 'Are you sure you want to quit?' ); "msg".blink(); "msg".fontsize(7);
8
2712
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") **************************** supposing that, there is a string array like
0
8683
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...
0
8611
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
9170
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
9031
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
8904
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
8876
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
4624
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3052
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
3
2007
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.