Reputation: 5716
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
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
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
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