Vladimir Yanakiev Vladimir Yanakiev - 1 month ago 5
C++ Question

why auto doesn't detect reference type of function

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?

Answer

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: