Is it safe to use c_str() on a temporary string? The Next CEO of Stack OverflowIs 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?

Chain wire methods together in Lightning Web Components

Is it possible to replace duplicates of a character with one character using tr

Should I tutor a student who I know has cheated on their homework?

Does soap repel water?

The exact meaning of 'Mom made me a sandwich'

A Man With a Stainless Steel Endoskeleton (like The Terminator) Fighting Cloaked Aliens Only He Can See

Why isn't acceleration always zero whenever velocity is zero, such as the moment a ball bounces off a wall?

WOW air has ceased operation, can I get my tickets refunded?

Bartok - Syncopation (1): Meaning of notes in between Grand Staff

Why do airplanes bank sharply to the right after air-to-air refueling?

Is it ever safe to open a suspicious HTML file (e.g. email attachment)?

Math-accent symbol over parentheses enclosing accented symbol (amsmath)

How many extra stops do monopods offer for tele photographs?

Would this house-rule that treats advantage as a +1 to the roll instead (and disadvantage as -1) and allows them to stack be balanced?

What did we know about the Kessel run before the prequels?

Axiom Schema vs Axiom

Does Germany produce more waste than the US?

Find non-case sensitive string in a mixed list of elements?

Reference request: Grassmannian and Plucker coordinates in type B, C, D

Some questions about different axiomatic systems for neighbourhoods

When you upcast Blindness/Deafness, do all targets suffer the same effect?

Are police here, aren't itthey?

Would a completely good Muggle be able to use a wand?

"misplaced omit" error when >centering columns



Is it safe to use c_str() on a temporary string?



The Next CEO of Stack OverflowIs 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?










15















#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?










share|improve this question









New contributor




Aknin Abdo is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.















  • 1





    Where does that string that gets returned go after c_str() is called and returns a pointer to some data?

    – tadman
    2 days ago






  • 2





    stackoverflow.com/questions/23464504/…

    – Wyck
    2 days ago






  • 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
    2 days ago






  • 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
    2 days ago







  • 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
    2 days ago















15















#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?










share|improve this question









New contributor




Aknin Abdo is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.















  • 1





    Where does that string that gets returned go after c_str() is called and returns a pointer to some data?

    – tadman
    2 days ago






  • 2





    stackoverflow.com/questions/23464504/…

    – Wyck
    2 days ago






  • 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
    2 days ago






  • 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
    2 days ago







  • 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
    2 days ago













15












15








15








#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?










share|improve this question









New contributor




Aknin Abdo is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.












#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






share|improve this question









New contributor




Aknin Abdo is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.











share|improve this question









New contributor




Aknin Abdo is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.









share|improve this question




share|improve this question








edited yesterday









Hong Ooi

43.1k1097139




43.1k1097139






New contributor




Aknin Abdo is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.









asked 2 days ago









Aknin AbdoAknin Abdo

815




815




New contributor




Aknin Abdo is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.





New contributor





Aknin Abdo is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.






Aknin Abdo is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.







  • 1





    Where does that string that gets returned go after c_str() is called and returns a pointer to some data?

    – tadman
    2 days ago






  • 2





    stackoverflow.com/questions/23464504/…

    – Wyck
    2 days ago






  • 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
    2 days ago






  • 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
    2 days ago







  • 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
    2 days ago












  • 1





    Where does that string that gets returned go after c_str() is called and returns a pointer to some data?

    – tadman
    2 days ago






  • 2





    stackoverflow.com/questions/23464504/…

    – Wyck
    2 days ago






  • 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
    2 days ago






  • 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
    2 days ago







  • 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
    2 days ago







1




1





Where does that string that gets returned go after c_str() is called and returns a pointer to some data?

– tadman
2 days ago





Where does that string that gets returned go after c_str() is called and returns a pointer to some data?

– tadman
2 days ago




2




2





stackoverflow.com/questions/23464504/…

– Wyck
2 days ago





stackoverflow.com/questions/23464504/…

– Wyck
2 days ago




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
2 days ago





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
2 days ago




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
2 days ago






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
2 days ago





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
2 days ago





@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
2 days ago












2 Answers
2






active

oldest

votes


















21














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;






share|improve this answer

























  • 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
    2 days ago







  • 6





    @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
    2 days ago






  • 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
    2 days ago






  • 1





    @Wyck a single statement can possibly have multiple sequencing considerations, but they would not affect when a temporary is destroyed

    – kmdreko
    2 days ago






  • 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
    yesterday


















10














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.






share|improve this answer




















  • 1





    A const reference, I think you mean.

    – Nemo
    yesterday






  • 1





    "If you bind a const reference to a temporary" Shouldn't that be "If you bind a temporary to a const reference"?

    – Rakete1111
    yesterday






  • 1





    @Rakete1111 - I don't think the order matters it's a 1-1 relationship.

    – Omnifarious
    23 hours ago











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
);



);






Aknin Abdo is a new contributor. Be nice, and check out our Code of Conduct.









draft saved

draft discarded


















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









21














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;






share|improve this answer

























  • 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
    2 days ago







  • 6





    @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
    2 days ago






  • 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
    2 days ago






  • 1





    @Wyck a single statement can possibly have multiple sequencing considerations, but they would not affect when a temporary is destroyed

    – kmdreko
    2 days ago






  • 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
    yesterday















21














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;






share|improve this answer

























  • 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
    2 days ago







  • 6





    @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
    2 days ago






  • 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
    2 days ago






  • 1





    @Wyck a single statement can possibly have multiple sequencing considerations, but they would not affect when a temporary is destroyed

    – kmdreko
    2 days ago






  • 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
    yesterday













21












21








21







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;






share|improve this answer















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;







share|improve this answer














share|improve this answer



share|improve this answer








edited 2 days ago

























answered 2 days ago









bolovbolov

33.3k877141




33.3k877141












  • 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
    2 days ago







  • 6





    @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
    2 days ago






  • 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
    2 days ago






  • 1





    @Wyck a single statement can possibly have multiple sequencing considerations, but they would not affect when a temporary is destroyed

    – kmdreko
    2 days ago






  • 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
    yesterday

















  • 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
    2 days ago







  • 6





    @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
    2 days ago






  • 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
    2 days ago






  • 1





    @Wyck a single statement can possibly have multiple sequencing considerations, but they would not affect when a temporary is destroyed

    – kmdreko
    2 days ago






  • 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
    yesterday
















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
2 days ago






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
2 days ago





6




6





@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
2 days ago





@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
2 days ago




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
2 days ago





@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
2 days ago




1




1





@Wyck a single statement can possibly have multiple sequencing considerations, but they would not affect when a temporary is destroyed

– kmdreko
2 days ago





@Wyck a single statement can possibly have multiple sequencing considerations, but they would not affect when a temporary is destroyed

– kmdreko
2 days ago




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
yesterday





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
yesterday













10














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.






share|improve this answer




















  • 1





    A const reference, I think you mean.

    – Nemo
    yesterday






  • 1





    "If you bind a const reference to a temporary" Shouldn't that be "If you bind a temporary to a const reference"?

    – Rakete1111
    yesterday






  • 1





    @Rakete1111 - I don't think the order matters it's a 1-1 relationship.

    – Omnifarious
    23 hours ago















10














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.






share|improve this answer




















  • 1





    A const reference, I think you mean.

    – Nemo
    yesterday






  • 1





    "If you bind a const reference to a temporary" Shouldn't that be "If you bind a temporary to a const reference"?

    – Rakete1111
    yesterday






  • 1





    @Rakete1111 - I don't think the order matters it's a 1-1 relationship.

    – Omnifarious
    23 hours ago













10












10








10







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.






share|improve this answer















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.







share|improve this answer














share|improve this answer



share|improve this answer








edited yesterday

























answered yesterday









OmnifariousOmnifarious

41.1k11101163




41.1k11101163







  • 1





    A const reference, I think you mean.

    – Nemo
    yesterday






  • 1





    "If you bind a const reference to a temporary" Shouldn't that be "If you bind a temporary to a const reference"?

    – Rakete1111
    yesterday






  • 1





    @Rakete1111 - I don't think the order matters it's a 1-1 relationship.

    – Omnifarious
    23 hours ago












  • 1





    A const reference, I think you mean.

    – Nemo
    yesterday






  • 1





    "If you bind a const reference to a temporary" Shouldn't that be "If you bind a temporary to a const reference"?

    – Rakete1111
    yesterday






  • 1





    @Rakete1111 - I don't think the order matters it's a 1-1 relationship.

    – Omnifarious
    23 hours ago







1




1





A const reference, I think you mean.

– Nemo
yesterday





A const reference, I think you mean.

– Nemo
yesterday




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
yesterday





"If you bind a const reference to a temporary" Shouldn't that be "If you bind a temporary to a const reference"?

– Rakete1111
yesterday




1




1





@Rakete1111 - I don't think the order matters it's a 1-1 relationship.

– Omnifarious
23 hours ago





@Rakete1111 - I don't think the order matters it's a 1-1 relationship.

– Omnifarious
23 hours ago










Aknin Abdo is a new contributor. Be nice, and check out our Code of Conduct.









draft saved

draft discarded


















Aknin Abdo is a new contributor. Be nice, and check out our Code of Conduct.












Aknin Abdo is a new contributor. Be nice, and check out our Code of Conduct.











Aknin Abdo is a new contributor. Be nice, and check out our Code of Conduct.














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.




draft saved


draft discarded














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





















































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







Popular posts from this blog

រឿង រ៉ូមេអូ និង ហ្ស៊ុយលីយេ សង្ខេបរឿង តួអង្គ បញ្ជីណែនាំ

QGIS export composer to PDF scale the map [closed] Planned maintenance scheduled April 23, 2019 at 23:30 UTC (7:30pm US/Eastern) Announcing the arrival of Valued Associate #679: Cesar Manara Unicorn Meta Zoo #1: Why another podcast?Print Composer QGIS 2.6, how to export image?QGIS 2.8.1 print composer won't export all OpenCycleMap base layer tilesSave Print/Map QGIS composer view as PNG/PDF using Python (without changing anything in visible layout)?Export QGIS Print Composer PDF with searchable text labelsQGIS Print Composer does not change from landscape to portrait orientation?How can I avoid map size and scale changes in print composer?Fuzzy PDF export in QGIS running on macSierra OSExport the legend into its 100% size using Print ComposerScale-dependent rendering in QGIS PDF output

PDF-ში გადმოწერა სანავიგაციო მენიუproject page