jeudi 15 avril 2021

Returns as value or as reference through parameter?

std::vector<std::string> get() {
    std::vector<string> result {};
    
    for (int i = 0; i < 10000) {
        result.emplace_back("test" + to_string(i));
    }

    return result;
}

//or
void get(std::vector<std::string>& result) {
    
    for (int i = 0; i < 10000) {
        result.emplace_back("test" + to_string(i));
    }
}

//Is it more efficient to go through the reference than to return it? Or is copying elision and is it the same in terms of efficiency?

int main()
{
    auto arr = get();
    std::vector<std::string> arrPassingByRef{};
    get(arrPassingByRef);
}

Aucun commentaire:

Enregistrer un commentaire