Chesnokov Yuriy
Chesnokov Yuriy

Reputation: 1838

Reference, pointer or value semantics in C/C++ functions

I have simple code to trim the string

std::string TrimEnd(const std::string& str, const std::string& chars)
{
    std::string trimmed = str;
    int index = 0;
    if((index = trimmed.find_last_not_of(chars)) < trimmed.length() - 1)
            trimmed.erase(index + 1);
    return trimmed;
}

I use references for arguments and value for function return. Is there any preference to use pointers instead? In my case a copy of the trimmed string is returned. In some functions const reference is returned.

Upvotes: 1

Views: 1308

Answers (4)

Jon Purdy
Jon Purdy

Reputation: 55079

Here, since you’re making a copy of the first argument anyway, you may as well pass it by value:

std::string TrimEnd(std::string str, const std::string& chars)
{
    int index = 0;
    if((index = str.find_last_not_of(chars)) < str.length() - 1)
        str.erase(index + 1);
    return str;
}

In general:

  • Pass object types by const reference.

  • Pass primitives (e.g., int) by value, as well as object types when you need a mutable copy.

  • Pass parameters by pointer when that pointer may be null.

  • Return by value or smart pointer (e.g., unique_ptr); raw pointers have unclear ownership.

Upvotes: 0

evanmcdonnal
evanmcdonnal

Reputation: 48154

There's no reason to pass by reference if you return a new string, and you certainly don't want to return a reference to trimmed because it's scope is the TrimEnd method.

Unless you're trying to optimize your code I would pass by value. If you're writing your own string class (or something like that) and performance is your top priority, then I would do everything by reference.

Upvotes: 1

Dan
Dan

Reputation: 2119

For C++ style, you return by value. pass by reference/const reference. ( value for POD ) never return by reference unless it refers to static storage, or to a member variable if you want to expose access to them ( typically const & would be used for that).. yes the return by value generates yet another copy, however the older c++ standard allows compilers to optimize that out. And the new c++ 11 standard allows move constructors which are even more awesome.

Upvotes: 2

John Dibling
John Dibling

Reputation: 101506

No, not in a general sense. If you need to be able to pass in a NULL-ified pointer, or need to do some pointer arithmetic on the parameter, pass a pointer. Otherwise, pass references by default.

Upvotes: 2

Related Questions