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

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

8

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

Share
Improve this question

4

  • 2

    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

    11 hours ago

  • 1

    Some nearly-canonical documentation.

    – user4581301

    11 hours ago

  • 1

    I'm surprised I can't find a good duplicate of this. Closest I got is this.

    – Nelfeal

    11 hours ago

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

    – user4581301

    11 hours ago

1 Answer
1

Reset to default

Highest score (default)

Trending (recent votes count more)

Date modified (newest first)

Date created (oldest first)

7

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.

Share
Improve this answer

Your Answer

Draft saved
Draft discarded

Post as a guest

Required, but never shown


By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged

or ask your own question.

Leave a Reply

Your email address will not be published. Required fields are marked *