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.

BlueCannonBall
  • 365
  • 2
  • 5
  • 5
    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. – user4581301 Jul 28 '23 at 00:20
  • 2
    [Some nearly-canonical documentation](https://en.cppreference.com/w/cpp/language/lifetime#Temporary_object_lifetime). – user4581301 Jul 28 '23 at 00:24
  • 6
    I'm surprised I can't find a good duplicate of this. Closest I got is [this](https://stackoverflow.com/questions/73875331/is-it-an-ub-when-i-try-to-pass-the-address-of-temporary-as-argument). – Nelfeal Jul 28 '23 at 00:33
  • 3
    [Here's the canonical documentation](http://eel.is/c++draft/class.temporary#4) and [some supporting information on when the expression ends](http://eel.is/c++draft/intro.execution#5). 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. – user4581301 Jul 28 '23 at 00:35
  • 1
    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? – John Bollinger Jul 28 '23 at 20:25
  • 1
    @JohnBollinger It's just an example of a more general case. See the last sentence in the question. – Unmitigated Jul 28 '23 at 22:33
  • @Nelfeal Plenty of good duplicates to choose from: https://www.google.com/search?q=c_str+as+temporary+site:stackoverflow.com – Cody Gray - on strike Jul 29 '23 at 00:41

1 Answers1

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.

user17732522
  • 53,019
  • 2
  • 56
  • 105