Is constructing an object in an argument list and passing a pointer to internal data of the object to the function safe?
Asked Answered
L

1

21

Is the C++ code below well-formed? Will the std::string get destroyed before or after the function finishes executing?

void my_function(const char*);

...

my_function(std::string("Something").c_str());

I know I could do my_function("Something"), but I am using std::string this way to illustrate my point.

Lombroso answered 28/7, 2023 at 0:17 Comment(7)
But seriously, the temporary string will die at the end of the expression. That'll be after the function call. So long as my_function doesn't store that pointer somewhere with a longer life you're good.Drucill
Some nearly-canonical documentation.Drucill
I'm surprised I can't find a good duplicate of this. Closest I got is this.Purplish
Here's the canonical documentation and some supporting information on when the expression ends. Took longer to find than I thought it would. But go with the stuff at CPP reference. I reads like it was translated from Martian, but in a way that's because it was.Drucill
It's hard to fathom why you propose that construction over simply my_function("Something");. I mean, sure, std::string is widely favored over C strings in C++, but when you have a function that wants a const C string anyway, how does it make sense to use a std::string to make a temporary copy of a perfectly good C string to pass to it?Coil
@JohnBollinger It's just an example of a more general case. See the last sentence in the question.Lizbeth
@Purplish Plenty of good duplicates to choose from: google.com/search?q=c_str+as+temporary+site:stackoverflow.comUpandcoming
C
25

Will the std::string get destroyed before or after the function finishes executing?

Temporary objects are destroyed (with some exceptions, none relevant here) at the end of the full-expression in which they were materialized (e.g. typically the end of an expression statement).

The std::string object here is such a temporary materialized in the full-expression that spans the whole my_function(std::string("Something").c_str()); expression statement. So it is destroyed after my_function returns in your example.

Crossbill answered 28/7, 2023 at 0:26 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.