Search code examples
c++constantscorrectness

Const variable declaration


I have a function returning a const reference to an object as follows:

const &Foo getFoo() {
    return foo;
}

If I have another function as follows:

void bar() {
    const qwerty = asdf.getFoo();
    int x = qwerty.x + 5;
    // something here
}

Is preceding qwerty with const necessary or best practice?


Solution

  • Well, first of all, it's neither necessary nor best practice - it's insufficient. You need a type too. Once you fill that in, the const is still not necessary, unless you try to take it by non-const reference. We have three choices that could compile:

    Foo qwerty =  asdf.getFoo();       // (A)
    const Foo qwerty = asdf.getFoo();  // (B)
    const Foo& qwerty = asdf.getFoo(); // (C)
    

    Given that getFoo() returns a reference to const, the most efficient thing would be to take it as reference to const as well, that avoids a copy. Unless, that is, you want a copy - in which case do (A) or (B), depending on whether or not you want a modifiable copy or not. Unless Foo is non-copyable, in which case (C) is your only option anyway.

    Ultimately, it depends on what you want to do with qwerty. I would default to (C), and need a reason to pick one or the other instead.