NeatNit
NeatNit

Reputation: 632

Returning a const variable - can it cause problems?

I'm new to C++, haven't found an answer to this because the search results are always about the function signature and not this.

Basically, if I have a function:

std::string MyFunction(const int test) const
{
    const std::string str1 = "Hello";
    const std::string str2 = "World";
    return test > 7 ? str1 : str2;
}

The return value is either str1 or str2, which are both const. Can this cause problems for the caller?

Upvotes: 1

Views: 128

Answers (2)

R Sahu
R Sahu

Reputation: 206567

The return value is either str1 or str2, which are both const. Can this cause problems for the caller?

No, it won't. The returned object is a copy of one of those.

As an aside, the use of const in the argument type is pointless in most use cases. Whether you modify the value of the argument in the function or not does not impact the calling function. Unless you have a strong reason to justify use of const, I recommend using the simpler form without the const.

std::string MyFunction(int test) const { ... }

Upvotes: 3

Acorn
Acorn

Reputation: 26066

The type you are returning is std::string, not const std::string. The caller shouldn't care what the type of the local variables is (the caller may not even have access to the definition/body/implementation of the function!).

In general, the types of local variables in the body of a function cannot change the return type of the function itself (auto and lambdas excluded).

Upvotes: 3

Related Questions