Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When exactly are function arguments being destructed?

Tags:

I have a question because it is not clear to me when function arguments get destroyed. Therefore, is the concatenation of the following doSomething function error-prone or not?

I’m asking because "it is the programmer's responsibility to ensure that std::string_view does not outlive the pointed-to character array". Can that be guaranteed in that specific case or not?

#include <string>
#include <string_view>

std::string doSomething(const std::string_view& str_view)
{
    // do something and create a new std::string instance based on the std::string_view instance

    return str;
}

int main()
{
    std::string input_str{"Hello world!"};

    std::string output_str{ doSomething(doSomething(doSomething(input_str))) };

    return 0;
}
like image 903
D3V0N5H1R3 Avatar asked May 13 '21 14:05

D3V0N5H1R3


People also ask

Can destructors take arguments?

A destructor takes no arguments and has no return type. Its address cannot be taken. Destructors cannot be declared const , volatile , const volatile or static . A destructor can be declared virtual or pure virtual .

Which is used to separate the argument of a function?

The maximum number of arguments (and corresponding parameters) is 253 for a single function. Arguments are separated by commas. However, the comma is not an operator in this context, and the arguments can be evaluated by the compiler in any order.

What does it mean to pass a function arguments and what does that do?

Passing Functions as Arguments. Functions are data, and therefore can be passed around just like other values. This means a function can be passed to another function as an argument. This allows the function being called to use the function argument to carry out its action.

How many arguments is too many for a function?

The ideal number of arguments for a function is zero (niladic). Next comes one (monadic), followed closely by two (dyadic). Three arguments (triadic) should be avoided where possible. More than three (polyadic) requires very special justification - and then shouldn't be used anyway.


1 Answers

The anonymous temporary passed to the (const reference) parameter const std::string_view& str_view survives the function call.

Since there are nested functions, the anonymous temporaries are not destroyed until, conceptually, the closing semicolon of

std::string output_str{ doSomething(doSomething(doSomething(input_str))) };
like image 163
Bathsheba Avatar answered Sep 30 '22 16:09

Bathsheba