Is it safe to use c_str() on a temporary string?Is a string literal in c++ created in static memory?string and const char* and .c_str()?What is the difference between String and string in C#?How do I iterate over the words of a string?How do I read / convert an InputStream into a String in Java?Case insensitive 'Contains(string)'How do I make the first letter of a string uppercase in JavaScript?How to replace all occurrences of a string in JavaScriptHow to check whether a string contains a substring in JavaScript?Does Python have a string 'contains' substring method?How do I convert a String to an int in Java?Why is char[] preferred over String for passwords?
Are white and non-white police officers equally likely to kill black suspects?
What do the Banks children have against barley water?
Why did the Germans forbid the possession of pet pigeons in Rostov-on-Don in 1941?
Filling an area between two curves
What to wear for invited talk in Canada
Short story: alien planet where slow students are executed
"listening to me about as much as you're listening to this pole here"
Why isn't airport relocation done gradually?
Does it makes sense to buy a new cycle to learn riding?
Does a dangling wire really electrocute me if I'm standing in water?
What is GPS' 19 year rollover and does it present a cybersecurity issue?
How to manage monthly salary
How to answer pointed "are you quitting" questioning when I don't want them to suspect
Doomsday-clock for my fantasy planet
Landlord wants to switch my lease to a "Land contract" to "get back at the city"
What are the advantages and disadvantages of running one shots compared to campaigns?
Does light intensity oscillate really fast since it is a wave?
How did the USSR manage to innovate in an environment characterized by government censorship and high bureaucracy?
Unbreakable Formation vs. Cry of the Carnarium
Is a vector space a subspace of itself?
Ideas for 3rd eye abilities
How can I fix this gap between bookcases I made?
Typesetting a double Over Dot on top of a symbol
Shall I use personal or official e-mail account when registering to external websites for work purpose?
Is it safe to use c_str() on a temporary string?
Is a string literal in c++ created in static memory?string and const char* and .c_str()?What is the difference between String and string in C#?How do I iterate over the words of a string?How do I read / convert an InputStream into a String in Java?Case insensitive 'Contains(string)'How do I make the first letter of a string uppercase in JavaScript?How to replace all occurrences of a string in JavaScriptHow to check whether a string contains a substring in JavaScript?Does Python have a string 'contains' substring method?How do I convert a String to an int in Java?Why is char[] preferred over String for passwords?
.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty height:90px;width:728px;box-sizing:border-box;
#include <iostream>
std::string get_data()
return "Hello";
int main()
const char* data = get_data().c_str();
std::cout << data << "n";
return 0;
"Hello" is printing on my machine; however, I am led to believe that this behavior is unspecified i.e. implementation-specific. Am I correct or will it always print "Hello", judging that the returned string is immutable and as such qualified as something that is constant?
c++ string object-lifetime
|
show 8 more comments
#include <iostream>
std::string get_data()
return "Hello";
int main()
const char* data = get_data().c_str();
std::cout << data << "n";
return 0;
"Hello" is printing on my machine; however, I am led to believe that this behavior is unspecified i.e. implementation-specific. Am I correct or will it always print "Hello", judging that the returned string is immutable and as such qualified as something that is constant?
c++ string object-lifetime
1
Where does that string that gets returned go afterc_str()
is called and returns a pointer to some data?
– tadman
Mar 28 at 23:37
2
stackoverflow.com/questions/23464504/…
– Wyck
Mar 28 at 23:39
2
Probably not a duplicate but helpful: stackoverflow.com/questions/349025/…. Also your interview question is missing#include <string>
so technically it would be a compiler error ;)
– Tas
Mar 28 at 23:41
1
I'm a bit surprised that the documentation forstd::string::c_str
doesn't mention destruction of the string as grounds for the returned pointer being invalidated (unless you consider the destructor to be a non-const member function). I think many people coming from a C background would benefit from having this written explicitly
– alter igel
Mar 28 at 23:43
1
@Tas: io-streams implement the shift-operators including overloads on basic_string ,so it needs its definition which requires it to include <string>. So it can't be a compiler error.
– engf-010
Mar 28 at 23:59
|
show 8 more comments
#include <iostream>
std::string get_data()
return "Hello";
int main()
const char* data = get_data().c_str();
std::cout << data << "n";
return 0;
"Hello" is printing on my machine; however, I am led to believe that this behavior is unspecified i.e. implementation-specific. Am I correct or will it always print "Hello", judging that the returned string is immutable and as such qualified as something that is constant?
c++ string object-lifetime
#include <iostream>
std::string get_data()
return "Hello";
int main()
const char* data = get_data().c_str();
std::cout << data << "n";
return 0;
"Hello" is printing on my machine; however, I am led to believe that this behavior is unspecified i.e. implementation-specific. Am I correct or will it always print "Hello", judging that the returned string is immutable and as such qualified as something that is constant?
c++ string object-lifetime
c++ string object-lifetime
edited Mar 29 at 3:19
Hong Ooi
43.2k1097139
43.2k1097139
asked Mar 28 at 23:34
Aknin AbdoAknin Abdo
1215
1215
1
Where does that string that gets returned go afterc_str()
is called and returns a pointer to some data?
– tadman
Mar 28 at 23:37
2
stackoverflow.com/questions/23464504/…
– Wyck
Mar 28 at 23:39
2
Probably not a duplicate but helpful: stackoverflow.com/questions/349025/…. Also your interview question is missing#include <string>
so technically it would be a compiler error ;)
– Tas
Mar 28 at 23:41
1
I'm a bit surprised that the documentation forstd::string::c_str
doesn't mention destruction of the string as grounds for the returned pointer being invalidated (unless you consider the destructor to be a non-const member function). I think many people coming from a C background would benefit from having this written explicitly
– alter igel
Mar 28 at 23:43
1
@Tas: io-streams implement the shift-operators including overloads on basic_string ,so it needs its definition which requires it to include <string>. So it can't be a compiler error.
– engf-010
Mar 28 at 23:59
|
show 8 more comments
1
Where does that string that gets returned go afterc_str()
is called and returns a pointer to some data?
– tadman
Mar 28 at 23:37
2
stackoverflow.com/questions/23464504/…
– Wyck
Mar 28 at 23:39
2
Probably not a duplicate but helpful: stackoverflow.com/questions/349025/…. Also your interview question is missing#include <string>
so technically it would be a compiler error ;)
– Tas
Mar 28 at 23:41
1
I'm a bit surprised that the documentation forstd::string::c_str
doesn't mention destruction of the string as grounds for the returned pointer being invalidated (unless you consider the destructor to be a non-const member function). I think many people coming from a C background would benefit from having this written explicitly
– alter igel
Mar 28 at 23:43
1
@Tas: io-streams implement the shift-operators including overloads on basic_string ,so it needs its definition which requires it to include <string>. So it can't be a compiler error.
– engf-010
Mar 28 at 23:59
1
1
Where does that string that gets returned go after
c_str()
is called and returns a pointer to some data?– tadman
Mar 28 at 23:37
Where does that string that gets returned go after
c_str()
is called and returns a pointer to some data?– tadman
Mar 28 at 23:37
2
2
stackoverflow.com/questions/23464504/…
– Wyck
Mar 28 at 23:39
stackoverflow.com/questions/23464504/…
– Wyck
Mar 28 at 23:39
2
2
Probably not a duplicate but helpful: stackoverflow.com/questions/349025/…. Also your interview question is missing
#include <string>
so technically it would be a compiler error ;)– Tas
Mar 28 at 23:41
Probably not a duplicate but helpful: stackoverflow.com/questions/349025/…. Also your interview question is missing
#include <string>
so technically it would be a compiler error ;)– Tas
Mar 28 at 23:41
1
1
I'm a bit surprised that the documentation for
std::string::c_str
doesn't mention destruction of the string as grounds for the returned pointer being invalidated (unless you consider the destructor to be a non-const member function). I think many people coming from a C background would benefit from having this written explicitly– alter igel
Mar 28 at 23:43
I'm a bit surprised that the documentation for
std::string::c_str
doesn't mention destruction of the string as grounds for the returned pointer being invalidated (unless you consider the destructor to be a non-const member function). I think many people coming from a C background would benefit from having this written explicitly– alter igel
Mar 28 at 23:43
1
1
@Tas: io-streams implement the shift-operators including overloads on basic_string ,so it needs its definition which requires it to include <string>. So it can't be a compiler error.
– engf-010
Mar 28 at 23:59
@Tas: io-streams implement the shift-operators including overloads on basic_string ,so it needs its definition which requires it to include <string>. So it can't be a compiler error.
– engf-010
Mar 28 at 23:59
|
show 8 more comments
2 Answers
2
active
oldest
votes
The code exhibits undefined behavior.
get_data()
returns a temporary which expires at the end of the full expression (*):
const char* data = get_data().c_str() ;
// ^~~~~~~~~~ ^
// this evaluates |
// to a prvalue |
// temporary expires here
data
points to an internal of that object, so after the temporary ends you are left with a dangling pointer. Accessing it leads to Undefined Behavior. So the next line std::cout << data << "n";
makes the whole program exhibit Undefined Behavior.
*) There is an exception to this rule which doesn't apply here. If a prvalue is directly bound to a reference, the lifetime of the prvalue is extended to the lifetime of the reference.
For instance, this would have been fine:
int main()
const std::string& ref = get_data();
const char* data = ref.c_str();
std::cout << data << "n";
return 0;
Your answer should include something with the words sequence point to get my upvote, because people still search for that - even though it doesn't appear in the standard.
– Wyck
Mar 28 at 23:47
8
@Wyck I don't see how sequence points are relevant here. The only thing that matters is the lifetime of the temporary. And that lifetime is until the end of the full expression it appears on.
– bolov
Mar 28 at 23:49
4
@Wyck newer standards don't use "sequence points" indeed. They use "sequenced after" and "sequenced before". I still don't see the connection to the problem at hand... Maybe I am missing something, could you please tell how sequencing relates here?
– bolov
Mar 28 at 23:51
1
@Wyck a single statement can possibly have multiple sequencing considerations, but they would not affect when a temporary is destroyed
– kmdreko
Mar 28 at 23:54
1
The only thing that this doesn't cover is the Asker's statement that judging that the returned string is immutable suggests that they might not know that the string literal and the returnedstd::string
are separate objects.
– user4581301
Mar 29 at 0:35
|
show 2 more comments
Yes it is, but not the way you're doing it.
If you did this:
std::cout << get_data().c_str() << 'n';
you'd be just fine.
That's because a temporary is guaranteed to live for the lifetime of the full expression it was created in. It may live longer in certain, very specific circumstances.
If you bind a const reference to a temporary, it's lifetime will be extended to be the lifetime of the name it was bound to. So, code like this:
std::string const &x = get_data();
std::cout << x.c_str() << 'n';
would also work because the temporary returned by get_data
would be bound to the reference named x
, and so as long as x
remained a valid name to use, the temporary would still exist.
1
A const reference, I think you mean.
– Nemo
Mar 29 at 3:23
1
"If you bind a const reference to a temporary" Shouldn't that be "If you bind a temporary to a const reference"?
– Rakete1111
Mar 29 at 13:42
1
@Rakete1111 - I don't think the order matters it's a 1-1 relationship.
– Omnifarious
Mar 30 at 0:46
add a comment |
Your Answer
StackExchange.ifUsing("editor", function ()
StackExchange.using("externalEditor", function ()
StackExchange.using("snippets", function ()
StackExchange.snippets.init();
);
);
, "code-snippets");
StackExchange.ready(function()
var channelOptions =
tags: "".split(" "),
id: "1"
;
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function()
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled)
StackExchange.using("snippets", function()
createEditor();
);
else
createEditor();
);
function createEditor()
StackExchange.prepareEditor(
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader:
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
,
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
);
);
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55408411%2fis-it-safe-to-use-c-str-on-a-temporary-string%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
2 Answers
2
active
oldest
votes
2 Answers
2
active
oldest
votes
active
oldest
votes
active
oldest
votes
The code exhibits undefined behavior.
get_data()
returns a temporary which expires at the end of the full expression (*):
const char* data = get_data().c_str() ;
// ^~~~~~~~~~ ^
// this evaluates |
// to a prvalue |
// temporary expires here
data
points to an internal of that object, so after the temporary ends you are left with a dangling pointer. Accessing it leads to Undefined Behavior. So the next line std::cout << data << "n";
makes the whole program exhibit Undefined Behavior.
*) There is an exception to this rule which doesn't apply here. If a prvalue is directly bound to a reference, the lifetime of the prvalue is extended to the lifetime of the reference.
For instance, this would have been fine:
int main()
const std::string& ref = get_data();
const char* data = ref.c_str();
std::cout << data << "n";
return 0;
Your answer should include something with the words sequence point to get my upvote, because people still search for that - even though it doesn't appear in the standard.
– Wyck
Mar 28 at 23:47
8
@Wyck I don't see how sequence points are relevant here. The only thing that matters is the lifetime of the temporary. And that lifetime is until the end of the full expression it appears on.
– bolov
Mar 28 at 23:49
4
@Wyck newer standards don't use "sequence points" indeed. They use "sequenced after" and "sequenced before". I still don't see the connection to the problem at hand... Maybe I am missing something, could you please tell how sequencing relates here?
– bolov
Mar 28 at 23:51
1
@Wyck a single statement can possibly have multiple sequencing considerations, but they would not affect when a temporary is destroyed
– kmdreko
Mar 28 at 23:54
1
The only thing that this doesn't cover is the Asker's statement that judging that the returned string is immutable suggests that they might not know that the string literal and the returnedstd::string
are separate objects.
– user4581301
Mar 29 at 0:35
|
show 2 more comments
The code exhibits undefined behavior.
get_data()
returns a temporary which expires at the end of the full expression (*):
const char* data = get_data().c_str() ;
// ^~~~~~~~~~ ^
// this evaluates |
// to a prvalue |
// temporary expires here
data
points to an internal of that object, so after the temporary ends you are left with a dangling pointer. Accessing it leads to Undefined Behavior. So the next line std::cout << data << "n";
makes the whole program exhibit Undefined Behavior.
*) There is an exception to this rule which doesn't apply here. If a prvalue is directly bound to a reference, the lifetime of the prvalue is extended to the lifetime of the reference.
For instance, this would have been fine:
int main()
const std::string& ref = get_data();
const char* data = ref.c_str();
std::cout << data << "n";
return 0;
Your answer should include something with the words sequence point to get my upvote, because people still search for that - even though it doesn't appear in the standard.
– Wyck
Mar 28 at 23:47
8
@Wyck I don't see how sequence points are relevant here. The only thing that matters is the lifetime of the temporary. And that lifetime is until the end of the full expression it appears on.
– bolov
Mar 28 at 23:49
4
@Wyck newer standards don't use "sequence points" indeed. They use "sequenced after" and "sequenced before". I still don't see the connection to the problem at hand... Maybe I am missing something, could you please tell how sequencing relates here?
– bolov
Mar 28 at 23:51
1
@Wyck a single statement can possibly have multiple sequencing considerations, but they would not affect when a temporary is destroyed
– kmdreko
Mar 28 at 23:54
1
The only thing that this doesn't cover is the Asker's statement that judging that the returned string is immutable suggests that they might not know that the string literal and the returnedstd::string
are separate objects.
– user4581301
Mar 29 at 0:35
|
show 2 more comments
The code exhibits undefined behavior.
get_data()
returns a temporary which expires at the end of the full expression (*):
const char* data = get_data().c_str() ;
// ^~~~~~~~~~ ^
// this evaluates |
// to a prvalue |
// temporary expires here
data
points to an internal of that object, so after the temporary ends you are left with a dangling pointer. Accessing it leads to Undefined Behavior. So the next line std::cout << data << "n";
makes the whole program exhibit Undefined Behavior.
*) There is an exception to this rule which doesn't apply here. If a prvalue is directly bound to a reference, the lifetime of the prvalue is extended to the lifetime of the reference.
For instance, this would have been fine:
int main()
const std::string& ref = get_data();
const char* data = ref.c_str();
std::cout << data << "n";
return 0;
The code exhibits undefined behavior.
get_data()
returns a temporary which expires at the end of the full expression (*):
const char* data = get_data().c_str() ;
// ^~~~~~~~~~ ^
// this evaluates |
// to a prvalue |
// temporary expires here
data
points to an internal of that object, so after the temporary ends you are left with a dangling pointer. Accessing it leads to Undefined Behavior. So the next line std::cout << data << "n";
makes the whole program exhibit Undefined Behavior.
*) There is an exception to this rule which doesn't apply here. If a prvalue is directly bound to a reference, the lifetime of the prvalue is extended to the lifetime of the reference.
For instance, this would have been fine:
int main()
const std::string& ref = get_data();
const char* data = ref.c_str();
std::cout << data << "n";
return 0;
edited Mar 28 at 23:52
answered Mar 28 at 23:41
bolovbolov
33.8k878141
33.8k878141
Your answer should include something with the words sequence point to get my upvote, because people still search for that - even though it doesn't appear in the standard.
– Wyck
Mar 28 at 23:47
8
@Wyck I don't see how sequence points are relevant here. The only thing that matters is the lifetime of the temporary. And that lifetime is until the end of the full expression it appears on.
– bolov
Mar 28 at 23:49
4
@Wyck newer standards don't use "sequence points" indeed. They use "sequenced after" and "sequenced before". I still don't see the connection to the problem at hand... Maybe I am missing something, could you please tell how sequencing relates here?
– bolov
Mar 28 at 23:51
1
@Wyck a single statement can possibly have multiple sequencing considerations, but they would not affect when a temporary is destroyed
– kmdreko
Mar 28 at 23:54
1
The only thing that this doesn't cover is the Asker's statement that judging that the returned string is immutable suggests that they might not know that the string literal and the returnedstd::string
are separate objects.
– user4581301
Mar 29 at 0:35
|
show 2 more comments
Your answer should include something with the words sequence point to get my upvote, because people still search for that - even though it doesn't appear in the standard.
– Wyck
Mar 28 at 23:47
8
@Wyck I don't see how sequence points are relevant here. The only thing that matters is the lifetime of the temporary. And that lifetime is until the end of the full expression it appears on.
– bolov
Mar 28 at 23:49
4
@Wyck newer standards don't use "sequence points" indeed. They use "sequenced after" and "sequenced before". I still don't see the connection to the problem at hand... Maybe I am missing something, could you please tell how sequencing relates here?
– bolov
Mar 28 at 23:51
1
@Wyck a single statement can possibly have multiple sequencing considerations, but they would not affect when a temporary is destroyed
– kmdreko
Mar 28 at 23:54
1
The only thing that this doesn't cover is the Asker's statement that judging that the returned string is immutable suggests that they might not know that the string literal and the returnedstd::string
are separate objects.
– user4581301
Mar 29 at 0:35
Your answer should include something with the words sequence point to get my upvote, because people still search for that - even though it doesn't appear in the standard.
– Wyck
Mar 28 at 23:47
Your answer should include something with the words sequence point to get my upvote, because people still search for that - even though it doesn't appear in the standard.
– Wyck
Mar 28 at 23:47
8
8
@Wyck I don't see how sequence points are relevant here. The only thing that matters is the lifetime of the temporary. And that lifetime is until the end of the full expression it appears on.
– bolov
Mar 28 at 23:49
@Wyck I don't see how sequence points are relevant here. The only thing that matters is the lifetime of the temporary. And that lifetime is until the end of the full expression it appears on.
– bolov
Mar 28 at 23:49
4
4
@Wyck newer standards don't use "sequence points" indeed. They use "sequenced after" and "sequenced before". I still don't see the connection to the problem at hand... Maybe I am missing something, could you please tell how sequencing relates here?
– bolov
Mar 28 at 23:51
@Wyck newer standards don't use "sequence points" indeed. They use "sequenced after" and "sequenced before". I still don't see the connection to the problem at hand... Maybe I am missing something, could you please tell how sequencing relates here?
– bolov
Mar 28 at 23:51
1
1
@Wyck a single statement can possibly have multiple sequencing considerations, but they would not affect when a temporary is destroyed
– kmdreko
Mar 28 at 23:54
@Wyck a single statement can possibly have multiple sequencing considerations, but they would not affect when a temporary is destroyed
– kmdreko
Mar 28 at 23:54
1
1
The only thing that this doesn't cover is the Asker's statement that judging that the returned string is immutable suggests that they might not know that the string literal and the returned
std::string
are separate objects.– user4581301
Mar 29 at 0:35
The only thing that this doesn't cover is the Asker's statement that judging that the returned string is immutable suggests that they might not know that the string literal and the returned
std::string
are separate objects.– user4581301
Mar 29 at 0:35
|
show 2 more comments
Yes it is, but not the way you're doing it.
If you did this:
std::cout << get_data().c_str() << 'n';
you'd be just fine.
That's because a temporary is guaranteed to live for the lifetime of the full expression it was created in. It may live longer in certain, very specific circumstances.
If you bind a const reference to a temporary, it's lifetime will be extended to be the lifetime of the name it was bound to. So, code like this:
std::string const &x = get_data();
std::cout << x.c_str() << 'n';
would also work because the temporary returned by get_data
would be bound to the reference named x
, and so as long as x
remained a valid name to use, the temporary would still exist.
1
A const reference, I think you mean.
– Nemo
Mar 29 at 3:23
1
"If you bind a const reference to a temporary" Shouldn't that be "If you bind a temporary to a const reference"?
– Rakete1111
Mar 29 at 13:42
1
@Rakete1111 - I don't think the order matters it's a 1-1 relationship.
– Omnifarious
Mar 30 at 0:46
add a comment |
Yes it is, but not the way you're doing it.
If you did this:
std::cout << get_data().c_str() << 'n';
you'd be just fine.
That's because a temporary is guaranteed to live for the lifetime of the full expression it was created in. It may live longer in certain, very specific circumstances.
If you bind a const reference to a temporary, it's lifetime will be extended to be the lifetime of the name it was bound to. So, code like this:
std::string const &x = get_data();
std::cout << x.c_str() << 'n';
would also work because the temporary returned by get_data
would be bound to the reference named x
, and so as long as x
remained a valid name to use, the temporary would still exist.
1
A const reference, I think you mean.
– Nemo
Mar 29 at 3:23
1
"If you bind a const reference to a temporary" Shouldn't that be "If you bind a temporary to a const reference"?
– Rakete1111
Mar 29 at 13:42
1
@Rakete1111 - I don't think the order matters it's a 1-1 relationship.
– Omnifarious
Mar 30 at 0:46
add a comment |
Yes it is, but not the way you're doing it.
If you did this:
std::cout << get_data().c_str() << 'n';
you'd be just fine.
That's because a temporary is guaranteed to live for the lifetime of the full expression it was created in. It may live longer in certain, very specific circumstances.
If you bind a const reference to a temporary, it's lifetime will be extended to be the lifetime of the name it was bound to. So, code like this:
std::string const &x = get_data();
std::cout << x.c_str() << 'n';
would also work because the temporary returned by get_data
would be bound to the reference named x
, and so as long as x
remained a valid name to use, the temporary would still exist.
Yes it is, but not the way you're doing it.
If you did this:
std::cout << get_data().c_str() << 'n';
you'd be just fine.
That's because a temporary is guaranteed to live for the lifetime of the full expression it was created in. It may live longer in certain, very specific circumstances.
If you bind a const reference to a temporary, it's lifetime will be extended to be the lifetime of the name it was bound to. So, code like this:
std::string const &x = get_data();
std::cout << x.c_str() << 'n';
would also work because the temporary returned by get_data
would be bound to the reference named x
, and so as long as x
remained a valid name to use, the temporary would still exist.
edited Mar 29 at 3:43
answered Mar 29 at 0:59
OmnifariousOmnifarious
41.2k11101163
41.2k11101163
1
A const reference, I think you mean.
– Nemo
Mar 29 at 3:23
1
"If you bind a const reference to a temporary" Shouldn't that be "If you bind a temporary to a const reference"?
– Rakete1111
Mar 29 at 13:42
1
@Rakete1111 - I don't think the order matters it's a 1-1 relationship.
– Omnifarious
Mar 30 at 0:46
add a comment |
1
A const reference, I think you mean.
– Nemo
Mar 29 at 3:23
1
"If you bind a const reference to a temporary" Shouldn't that be "If you bind a temporary to a const reference"?
– Rakete1111
Mar 29 at 13:42
1
@Rakete1111 - I don't think the order matters it's a 1-1 relationship.
– Omnifarious
Mar 30 at 0:46
1
1
A const reference, I think you mean.
– Nemo
Mar 29 at 3:23
A const reference, I think you mean.
– Nemo
Mar 29 at 3:23
1
1
"If you bind a const reference to a temporary" Shouldn't that be "If you bind a temporary to a const reference"?
– Rakete1111
Mar 29 at 13:42
"If you bind a const reference to a temporary" Shouldn't that be "If you bind a temporary to a const reference"?
– Rakete1111
Mar 29 at 13:42
1
1
@Rakete1111 - I don't think the order matters it's a 1-1 relationship.
– Omnifarious
Mar 30 at 0:46
@Rakete1111 - I don't think the order matters it's a 1-1 relationship.
– Omnifarious
Mar 30 at 0:46
add a comment |
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55408411%2fis-it-safe-to-use-c-str-on-a-temporary-string%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
1
Where does that string that gets returned go after
c_str()
is called and returns a pointer to some data?– tadman
Mar 28 at 23:37
2
stackoverflow.com/questions/23464504/…
– Wyck
Mar 28 at 23:39
2
Probably not a duplicate but helpful: stackoverflow.com/questions/349025/…. Also your interview question is missing
#include <string>
so technically it would be a compiler error ;)– Tas
Mar 28 at 23:41
1
I'm a bit surprised that the documentation for
std::string::c_str
doesn't mention destruction of the string as grounds for the returned pointer being invalidated (unless you consider the destructor to be a non-const member function). I think many people coming from a C background would benefit from having this written explicitly– alter igel
Mar 28 at 23:43
1
@Tas: io-streams implement the shift-operators including overloads on basic_string ,so it needs its definition which requires it to include <string>. So it can't be a compiler error.
– engf-010
Mar 28 at 23:59