I have studied auto
and I know it deduces types from initialized values. If I tried to write some guidelines for usage of auto
, can I put below statements as rules?
- Use
auto &&
for all values (r-values and l-value, as it is an universal ref) that are modifiable, auto &&
even for read only values,- Use
auto
wherever possible (individual preference for coding style).
EDIT
class Test
{
public:
Test() = default;
Test(const Test&) = default;
Test(Test&&) = default;
int i = 1;
};
Test getObj()
{
return Test();
}
Test& getObjByRef()
{
static Test tobj;
return tobj;
}
const Test getObjConst()
{
return Test();
}
int main()
{
auto && obj1 = getObj();
obj1.i = 2;
std::cout << " getObj returns: " << getObj().i << std::endl;
auto&& obj2 = getObjByRef();
obj2.i = 3;
std::cout << " getObjByRef returns: " << getObjByRef().i << std::endl;
auto && obj3 = getObjConst();
//obj3.i = 4; => //Error C3490 'i' cannot be modified because it is being accessed through a const object
return 0;
}
So in above example i used auto &&
for all three functions
getObj
getObjByRef
getObjConst
and it works as expected. Now can I conclude that:
auto &&
can be used to hold(initialize) any value, OR- We can use
auto &&
every possible place.
Do you see any pitfall of this approach?