Subway
Subway

Reputation: 5716

c++ Right way to store a private variable returned by reference

Consider this class:

class example
{

    inline const A& GetA()
    {
        return _a;
    }

private:
    A _a;
};

With the following code:

example Ex;
A& a = Ex.GetA();

_a will be returned by reference without making any copy of _a.

My question is what happens if I drop the reference operator as follows:

example Ex;
A a = Ex.GetA();

Will a be a reference to _a or a copy of _a will be created?

Upvotes: 0

Views: 360

Answers (3)

c0d3r
c0d3r

Reputation: 21

You could simple check by this code sample:

#include <iostream>

class A {
public:
    A() {
        std::cout << "Creating A from default ctor" << std::endl;
    }
    A(const A &) {
        std::cout << "A copy created!" << std::endl;
    }
};

class Example {
public:
        inline A& getA() {
            return _a;
        }

    private:
        A _a;
};

int main() {
Example a;
A aa = a.getA();

return 0;
}

Upvotes: 0

Mark B
Mark B

Reputation: 96281

In your second example, you've declared a local variable (not a reference) so you will get a copy of the reference value returned from your function.

That said: Don't do this. A public non-const method that returns by non-const reference is only one tiny step better than a struct with public members at a complexity cost. Just use the struct with public members and direct access instead OR properly encapsulate your data.

Upvotes: 1

Mike Seymour
Mike Seymour

Reputation: 254621

It will be a copy, if there is an accessible copy constructor, and a compile error otherwise. A variable is only a reference if you declare it to be one.

Upvotes: 4

Related Questions