1

What is the modern approach when it comes to returning two values (e.g. a vector and a bool)?

This one:

bool tokenize( const std::string_view inputStr, const std::size_t expectedTokenCount,
               std::vector< std::string >& foundTokens )
{
    // fill foundTokens which has been declared in the call site
}

or this one:

auto tokenize( const std::string_view inputStr, const std::size_t expectedTokenCount )
{
    std::vector< std::string > foundTokens;

    // fill foundTokens which is a local variable

    bool isValid = true;

    return std::make_pair< bool, std::vector<std::string> >( std::move( isValid ),
                                                             std::move( foundTokens ) );
}

or maybe another approach?

Any advice is appreciated.

digito_evo
  • 3,216
  • 2
  • 14
  • 42
  • you have some modern C++17 answers on the dupe – bolov Dec 18 '21 at 08:25
  • @bolov I don't understand. – digito_evo Dec 18 '21 at 08:26
  • 1
    There aren't *idiomatic* approaches. There are *options* that are each suitable in some circumstances and not others. These options include returning a `std::pair`, returning some other user-defined type that contains the desired pair of values (possibly with additional values), passing one or both values as reference arguments to be filled. – Peter Dec 18 '21 at 08:27
  • @digito_evo what is it you are having problems with? – bolov Dec 18 '21 at 08:30
  • @bolov I want to know if returning a `pair` is bad in terms of efficiency or not. How many bytes will be copied in this approach? 24+1? `vector` is 24 bytes on my compiler. – digito_evo Dec 18 '21 at 08:36
  • 1
    @digito_evo that's not what your question says. Anyway the answer is there is no copy thanks to the new C++17 temporary materialization rules. – bolov Dec 18 '21 at 09:07
  • @bolov So in this case by returning a pair, no copy will be made, right? You mean 0 bytes? – digito_evo Dec 18 '21 at 10:15
  • 3
    @digito_evo instead of `pair` it's better to return `std::optional` – phuclv Dec 18 '21 at 10:47
  • @phuclv But then how will it return the bool flag? – digito_evo Dec 18 '21 at 10:50
  • 1
    @digito_evo it's wrapped by the `std::optional` class. Read the documentation first and you'll see how it works – phuclv Dec 18 '21 at 10:53
  • 1
    std::optional is suitable, iff the bool specifies, whether the vector is valid – Sebastian Dec 18 '21 at 17:18
  • 2
    @phuclv Thank you for the suggestion. Using `std::optional` made my code more readable. – digito_evo Dec 20 '21 at 09:04

0 Answers0