0

I made a class with method, which returns reference to member (not good encapsulation). I'm using auto for retuned funtion

class classA
{
    public:
    classA(classA & rhs)
    {
        cout<<"copy constr A"<<endl;
    };
    classA() = default;
};

class classB
{
    private:
    classA obA;
    public:
        classA& getRefA(){return obA;}
};

int main()
{
    classB obB;

    auto ob = obB.getRefA();
 }

The result is copy constr A

I understand that auto don't detect reference from function. Is auto detecting only the type without reference?

erip
  • 16,374
  • 11
  • 66
  • 121
Vladimir Yanakiev
  • 1,240
  • 1
  • 16
  • 25
  • 2
    Yes. This is how the c++ type deduction works. Scott Meyes did a lot of talks about "type deduction" with auto so you can google for those to get some more information. Or pick up effective modern c++ by him. he has a whole chapter dedicated to this. – Hayt Oct 21 '16 at 11:22
  • 1
    [CppCon 2014: Scott Meyers "Type Deduction and Why You Care"](https://www.youtube.com/watch?v=wQxj20X-tIU) – Borgleader Oct 21 '16 at 12:05

2 Answers2

5

auto just by itself doesn't infer reference types. You can use auto& if you explicitly need a lvalue reference, or auto&& to use the reference collapsing rules for type inference.

If you need the type of an expression, use decltype. Keep in mind that there is a difference between decltype(x) and decltype((x)) -- the latter preserves references.

More resources on that topic:

Community
  • 1
  • 1
TheOperator
  • 5,936
  • 29
  • 42
3

The short answer is because auto doesn't capture any reference. It also won't capture cv-qualifiers.

If you need this behavior, you should use decltype.

erip
  • 16,374
  • 11
  • 66
  • 121