What is the point of the 'auto' keyword?

后端 未结 8 905
暗喜
暗喜 2020-12-16 03:30

So I understand using var in C# makes sense because you have anonymous types that are compiler derived. C++ doesn\'t seem to have this feature (unless I\'m wron

8条回答
  •  眼角桃花
    2020-12-16 04:00

    It is well worth reading Herb Sutter's article Almost Always Auto for some great examples of why it's worth using auto over explicit types. The main advantages are the reduction in typing, and gives additional safety if the underlying types change. One of my favourite examples though is about how it reduces duplication. If you allocate on the stack then you'd use:

    MyClass c(param);
    

    However, if you want to create on the heap you need:

    MyClass* c=new MyClass(param);
    

    So you've had to duplicate the MyClass, but the RHS already forces the variable to be a MyClass pointer, so you can just use this instead:

    auto c=new MyClass(param);
    

    If you want to declare it as a unique_ptr then previously you would need:

    unique_ptr c=make_unique(param);
    

    which can be abbreviated to:

    auto c=make_unique(param);
    

提交回复
热议问题