Skip to content
  • Categories
  • Recent
  • Tags
  • Popular
  • World
  • Users
  • Groups
Skins
  • Light
  • Cerulean
  • Cosmo
  • Flatly
  • Journal
  • Litera
  • Lumen
  • Lux
  • Materia
  • Minty
  • Morph
  • Pulse
  • Sandstone
  • Simplex
  • Sketchy
  • Spacelab
  • United
  • Yeti
  • Zephyr
  • Dark
  • Cyborg
  • Darkly
  • Quartz
  • Slate
  • Solar
  • Superhero
  • Vapor

  • Default (No Skin)
  • No Skin
Collapse
Code Project
  1. Home
  2. The Lounge
  3. Modern C++ auto

Modern C++ auto

Scheduled Pinned Locked Moved The Lounge
c++javascriptquestion
37 Posts 19 Posters 0 Views 1 Watching
  • Oldest to Newest
  • Newest to Oldest
  • Most Votes
Reply
  • Reply as topic
Log in to reply
This topic has been deleted. Only users with topic management privileges can see it.
  • S steveb

    Is this just me? I am starting to see the "auto" keyword abuse growing to an extraordinary proportions. Reminds me of the "var" type in JavaScript or "void*" in C/C++. The program, where all variables are declared as void*, would be considered atrocious, yet auto seems to be littered like an empty beer cans nowadays.

    A Offline
    A Offline
    Andy Hoffmeyer
    wrote on last edited by
    #16

    The use of auto is not laziness, nor is it abusive. It is correct and idiomatic modern C++. Bjarne Stroustrup and most members of the ISO C++ standardization committee actively advocate for its use, to the point where AAA - Almost Always Auto - has become a common mantra. The simple fact is that, most of the time, the compiler is smarter than you, and understands your code on a level that you never could. Allowing the compiler to determine the type automatically, as often as possible, allows for optimizations that may not be possible if you coerce an explicit type. People who reject evolutionary features of C++ are the same sort of people who would reject fuel injection on cars, because they learned how to drive a car with a carburetor, so everyone else should be fine with it. Technology advances. Try to keep up, or be left behind.

    W D 2 Replies Last reply
    0
    • S steveb

      Is this just me? I am starting to see the "auto" keyword abuse growing to an extraordinary proportions. Reminds me of the "var" type in JavaScript or "void*" in C/C++. The program, where all variables are declared as void*, would be considered atrocious, yet auto seems to be littered like an empty beer cans nowadays.

      C Offline
      C Offline
      Carlosian
      wrote on last edited by
      #17

      I agree it can be easily abused. It is especially true if you are maintaining someone else's code. Yes, it's great for templated iterators and such, but it can also throw more work onto someone else down the road, which I consider rude or lazy. Say I need to add some functionality. I see

      auto foo = SomeFunctionReturningObjOrRef(bar);
      foo.SomeMethod(blah);

      Great. That's really easy for the original dev, and really easy for the compiler. Wonderful. Now I need to add some code. What the heck is a "foo"? What members does it have? What methods are available? Is it a base class, or a derived class that has the functions I need? The dev who wrote the code knew, but didn't bother to declare it. The compiler knows, and I suppose I can just try

      foo.SomeMethodIHopeTheObjectHas();

      And see if I get a compilation error. And hope that it really is the right type and not a base class or derived class of the one I expect... But practically speaking I have to do the work the original dev didn't do and look up

      SomeFunctionReturningObjOrRef()

      and see what it does, and what it returns so I can be sure I'm getting the right type or that it supports the methods I need, and I don't actually want to be using "bar" or something else or upcast or downcast etc.

      R 1 Reply Last reply
      0
      • M Member 9167057

        That's pretty much the point. In most cases, namely when the type doesn't matter as long as it works, the developer doesn't need to know. In edge cases, such as auto i=1 where i is required to be, let's say, an unsigned value somewhere later down the line, the developer can still forego the auto and make it a unsigned int i=1 or at least an auto i=static_cast1. An example from my own work: I've been using API functions like GetTickCount quite a lot and instead of looking up the exact return type, a simple auto s=GetTickCount does the job. API functions returning some value are documented as "Returns 0 if the operation succeeded", in that case, a if 0==s is still enough, I don't need to know the type.

        R Offline
        R Offline
        Rick Shaub
        wrote on last edited by
        #18

        Even "auto i=1" can be made explicit with "auto i=1U".

        1 Reply Last reply
        0
        • C Carlosian

          I agree it can be easily abused. It is especially true if you are maintaining someone else's code. Yes, it's great for templated iterators and such, but it can also throw more work onto someone else down the road, which I consider rude or lazy. Say I need to add some functionality. I see

          auto foo = SomeFunctionReturningObjOrRef(bar);
          foo.SomeMethod(blah);

          Great. That's really easy for the original dev, and really easy for the compiler. Wonderful. Now I need to add some code. What the heck is a "foo"? What members does it have? What methods are available? Is it a base class, or a derived class that has the functions I need? The dev who wrote the code knew, but didn't bother to declare it. The compiler knows, and I suppose I can just try

          foo.SomeMethodIHopeTheObjectHas();

          And see if I get a compilation error. And hope that it really is the right type and not a base class or derived class of the one I expect... But practically speaking I have to do the work the original dev didn't do and look up

          SomeFunctionReturningObjOrRef()

          and see what it does, and what it returns so I can be sure I'm getting the right type or that it supports the methods I need, and I don't actually want to be using "bar" or something else or upcast or downcast etc.

          R Offline
          R Offline
          Rick York
          wrote on last edited by
          #19

          I usually do "all that work" by hovering the mouse over the function call and seeing what the IDE shows as the prototype of the function. There is no guesswork involved.

          "They have a consciousness, they have a life, they have a soul! Damn you! Let the rabbits wear glasses! Save our brothers! Can I get an amen?"

          D 1 Reply Last reply
          0
          • A Andy Hoffmeyer

            The use of auto is not laziness, nor is it abusive. It is correct and idiomatic modern C++. Bjarne Stroustrup and most members of the ISO C++ standardization committee actively advocate for its use, to the point where AAA - Almost Always Auto - has become a common mantra. The simple fact is that, most of the time, the compiler is smarter than you, and understands your code on a level that you never could. Allowing the compiler to determine the type automatically, as often as possible, allows for optimizations that may not be possible if you coerce an explicit type. People who reject evolutionary features of C++ are the same sort of people who would reject fuel injection on cars, because they learned how to drive a car with a carburetor, so everyone else should be fine with it. Technology advances. Try to keep up, or be left behind.

            W Offline
            W Offline
            wheelman570z
            wrote on last edited by
            #20

            Andy Hoffmeyer wrote:

            The simple fact is that, most of the time, the compiler is smarter than you, and understands your code on a level that you never could. Allowing the compiler to determine the type automatically, as often as possible, allows for optimizations that may not be possible if you coerce an explicit type.

            So, by that logic if I was using an IDE with good intellisense and hovered over a variable declared initially with auto, which showed me what the omniscient compiler will decide the type should be, and then explicitly declared the variable to be that exact type it would somehow break the multi-dimensional optimization the compiler would perform. Are you seriously saying that or did I misread your comment??

            A 1 Reply Last reply
            0
            • A Andy Hoffmeyer

              The use of auto is not laziness, nor is it abusive. It is correct and idiomatic modern C++. Bjarne Stroustrup and most members of the ISO C++ standardization committee actively advocate for its use, to the point where AAA - Almost Always Auto - has become a common mantra. The simple fact is that, most of the time, the compiler is smarter than you, and understands your code on a level that you never could. Allowing the compiler to determine the type automatically, as often as possible, allows for optimizations that may not be possible if you coerce an explicit type. People who reject evolutionary features of C++ are the same sort of people who would reject fuel injection on cars, because they learned how to drive a car with a carburetor, so everyone else should be fine with it. Technology advances. Try to keep up, or be left behind.

              D Offline
              D Offline
              Dean Roddey
              wrote on last edited by
              #21

              The community is very much divided over AAA, so it's hardly a no brainer and being against it hardly makes one a Luddite. Of course the people who design the language and compilers aren't the people who are maintaining my code, so it's pretty easy for them to make such an assertion. And the compiler doesn't understand my code anywhere NEAR as well I do. If it did, then it would know that if I changed the right side of a statement that had a auto type to something wrong, that it was actually wrong, even if the new type was syntactically compatible with the code to follow (which might be really simple and only use some operators that many, many types would support.) But if course it wouldn't know that error if it sat down on it, because it has absolutely no idea what the INTENT of that code is or what the DESIGN of my code is. And so that would create a silent failure that isn't caught because I was too lazy to make my intent clear to the compiler, using what tools are available, and explicit types are a key indication of intent.

              Explorans limites defectum

              1 Reply Last reply
              0
              • W wheelman570z

                Andy Hoffmeyer wrote:

                The simple fact is that, most of the time, the compiler is smarter than you, and understands your code on a level that you never could. Allowing the compiler to determine the type automatically, as often as possible, allows for optimizations that may not be possible if you coerce an explicit type.

                So, by that logic if I was using an IDE with good intellisense and hovered over a variable declared initially with auto, which showed me what the omniscient compiler will decide the type should be, and then explicitly declared the variable to be that exact type it would somehow break the multi-dimensional optimization the compiler would perform. Are you seriously saying that or did I misread your comment??

                A Offline
                A Offline
                Andy Hoffmeyer
                wrote on last edited by
                #22

                You're performing a good bit of mental gymnastics to arrive at that interpretation of what I said. Clearly, if you know the exact type that would be deduced, there would be no penalty for explicitly using it.

                D 1 Reply Last reply
                0
                • A Andy Hoffmeyer

                  You're performing a good bit of mental gymnastics to arrive at that interpretation of what I said. Clearly, if you know the exact type that would be deduced, there would be no penalty for explicitly using it.

                  D Offline
                  D Offline
                  Dean Roddey
                  wrote on last edited by
                  #23

                  But you always DO know the type, well 99.9999% of the time. So clearly there's no penalty. So how exactly does the compiler know more than us, particularly enough to risk the potential silent bugs that auto could introduce?

                  Explorans limites defectum

                  R 1 Reply Last reply
                  0
                  • R Rick York

                    I usually do "all that work" by hovering the mouse over the function call and seeing what the IDE shows as the prototype of the function. There is no guesswork involved.

                    "They have a consciousness, they have a life, they have a soul! Damn you! Let the rabbits wear glasses! Save our brothers! Can I get an amen?"

                    D Offline
                    D Offline
                    Dean Roddey
                    wrote on last edited by
                    #24

                    Really the above isn't the issue. The issue is this:

                    auto whatever = GetSomething()
                    while (somecondition)
                    whatever++;

                    In a large code base, there are probably a hundred or more things that would be syntactically compatible with that, so that accidentally changing GetSomething(), either manually or via search and replace, such that it returned one of those types, would create a completely silent error. Is it going to happen every day? No, obviously not. But that's not the point. The point is that, this:

                    FailureCounter& failCnt = GetFailCounter();
                    while (somecondition)
                    failCnt++;

                    is just far less likely to be subject to such a silent error because you have to make two parallel errors for that to happen. You are expressing your intent to the compiler by using an explicit type, which is the only way the compiler can know if your intent is not being followed. And how much extra work did that take to get the extra safety? Almost nothing.

                    Explorans limites defectum

                    R 1 Reply Last reply
                    0
                    • D Dean Roddey

                      But you always DO know the type, well 99.9999% of the time. So clearly there's no penalty. So how exactly does the compiler know more than us, particularly enough to risk the potential silent bugs that auto could introduce?

                      Explorans limites defectum

                      R Offline
                      R Offline
                      Rick Shaub
                      wrote on last edited by
                      #25

                      Can you give an example of such silent bugs? In fact, I think the ISO C++ committee would probably be interested in hearing about these bugs so they could address them in the next release.

                      D 1 Reply Last reply
                      0
                      • R Rick Shaub

                        Can you give an example of such silent bugs? In fact, I think the ISO C++ committee would probably be interested in hearing about these bugs so they could address them in the next release.

                        D Offline
                        D Offline
                        Dean Roddey
                        wrote on last edited by
                        #26

                        I gave one below and I'm sure that they know about them and they cannot address this, because it's fundamental to why auto is dangerous.

                        auto whatever = GetSomething()
                        while (somecondition)
                        whatever++;

                        If you accidentally change the right side to anything that provides a ++ operator (anything that is syntactically valid for the loop), the compiler will never know that's wrong, because you are not providing the compiler with information about your intent. The compiler is only being given SYNTACTICAL guidance when you use auto, not SEMANTIC guidance, which is what it needs to help you in this situation. If you provide the actual type, then you are telling the compiler what your intent is, i.e. semantic information, and so you have to make two parallel errors in most cases for this to silently cause a bug. Otherwise, you won't know until you somehow realize that something isn't getting incremented as it should be which could have most likely been caught at compile time with explicit typing.

                        Explorans limites defectum

                        R 1 Reply Last reply
                        0
                        • D Dean Roddey

                          I gave one below and I'm sure that they know about them and they cannot address this, because it's fundamental to why auto is dangerous.

                          auto whatever = GetSomething()
                          while (somecondition)
                          whatever++;

                          If you accidentally change the right side to anything that provides a ++ operator (anything that is syntactically valid for the loop), the compiler will never know that's wrong, because you are not providing the compiler with information about your intent. The compiler is only being given SYNTACTICAL guidance when you use auto, not SEMANTIC guidance, which is what it needs to help you in this situation. If you provide the actual type, then you are telling the compiler what your intent is, i.e. semantic information, and so you have to make two parallel errors in most cases for this to silently cause a bug. Otherwise, you won't know until you somehow realize that something isn't getting incremented as it should be which could have most likely been caught at compile time with explicit typing.

                          Explorans limites defectum

                          R Offline
                          R Offline
                          Rick Shaub
                          wrote on last edited by
                          #27

                          That sounds like your API has issues. Functions are interface contracts and if you don't know that function's return type changed, then the interface has been broken. That's outside the scope of language keywords, in my opinion.

                          D B 2 Replies Last reply
                          0
                          • R Rick Shaub

                            That sounds like your API has issues. Functions are interface contracts and if you don't know that function's return type changed, then the interface has been broken. That's outside the scope of language keywords, in my opinion.

                            D Offline
                            D Offline
                            Dean Roddey
                            wrote on last edited by
                            #28

                            So you are saying only one class in the entire code base can have a ++ operator? Or a += operator? or an add() method or a push() method?

                            Explorans limites defectum

                            R 1 Reply Last reply
                            0
                            • D Dean Roddey

                              So you are saying only one class in the entire code base can have a ++ operator? Or a += operator? or an add() method or a push() method?

                              Explorans limites defectum

                              R Offline
                              R Offline
                              Rick Shaub
                              wrote on last edited by
                              #29

                              I never said anything even close to that. I am saying if the maintainer of the GetSomething() function changes the return type without informing the consumer, that's a major problem that has nothing to do with language features.

                              D 1 Reply Last reply
                              0
                              • R Rick Shaub

                                I never said anything even close to that. I am saying if the maintainer of the GetSomething() function changes the return type without informing the consumer, that's a major problem that has nothing to do with language features.

                                D Offline
                                D Offline
                                Dean Roddey
                                wrote on last edited by
                                #30

                                So you are saying that mistakes shouldn't happen? Of course GetSomething()'s return could be changed by accident, and that would get caught also. But the more likely scenario is that someone accidentally changes the call, either by editing the wrong thing, or by search and replace, so that something besides GetSomething() is being called. Either of those things would become silent failures that could be taken care of by using an explicit type. Are they going to happen every day? No, they won't. But it's those type of silent errors that are the killers. Those are the ones that suddenly six months later the code stops working in the field and no one understands why.

                                Explorans limites defectum

                                R 1 Reply Last reply
                                0
                                • D Dean Roddey

                                  Really the above isn't the issue. The issue is this:

                                  auto whatever = GetSomething()
                                  while (somecondition)
                                  whatever++;

                                  In a large code base, there are probably a hundred or more things that would be syntactically compatible with that, so that accidentally changing GetSomething(), either manually or via search and replace, such that it returned one of those types, would create a completely silent error. Is it going to happen every day? No, obviously not. But that's not the point. The point is that, this:

                                  FailureCounter& failCnt = GetFailCounter();
                                  while (somecondition)
                                  failCnt++;

                                  is just far less likely to be subject to such a silent error because you have to make two parallel errors for that to happen. You are expressing your intent to the compiler by using an explicit type, which is the only way the compiler can know if your intent is not being followed. And how much extra work did that take to get the extra safety? Almost nothing.

                                  Explorans limites defectum

                                  R Offline
                                  R Offline
                                  Rick York
                                  wrote on last edited by
                                  #31

                                  I always use the highest warning level available and set warnings to be failures and I have done this for many years. Since the auto keyboard has been available I have never seen a compiler allow anything through that could cause a failure.

                                  "They have a consciousness, they have a life, they have a soul! Damn you! Let the rabbits wear glasses! Save our brothers! Can I get an amen?"

                                  D 1 Reply Last reply
                                  0
                                  • R Rick York

                                    I always use the highest warning level available and set warnings to be failures and I have done this for many years. Since the auto keyboard has been available I have never seen a compiler allow anything through that could cause a failure.

                                    "They have a consciousness, they have a life, they have a soul! Damn you! Let the rabbits wear glasses! Save our brothers! Can I get an amen?"

                                    D Offline
                                    D Offline
                                    Dean Roddey
                                    wrote on last edited by
                                    #32

                                    There's nothing to warn about in the scenario I indicated. It's a completely valid program, just the wrong one.

                                    Explorans limites defectum

                                    1 Reply Last reply
                                    0
                                    • R Rick Shaub

                                      That sounds like your API has issues. Functions are interface contracts and if you don't know that function's return type changed, then the interface has been broken. That's outside the scope of language keywords, in my opinion.

                                      B Offline
                                      B Offline
                                      bVagadishnu
                                      wrote on last edited by
                                      #33

                                      but if memory serves, there was a call into SharePoint API that if there was a single result found it returned a string. If multiple results, returned an array of string. Found out the hard way to check the type of return before using the result(s).

                                      _______________________________________________________________ Ah don't lean on me man, cause you can't afford the ticket

                                      1 Reply Last reply
                                      0
                                      • S steveb

                                        Is this just me? I am starting to see the "auto" keyword abuse growing to an extraordinary proportions. Reminds me of the "var" type in JavaScript or "void*" in C/C++. The program, where all variables are declared as void*, would be considered atrocious, yet auto seems to be littered like an empty beer cans nowadays.

                                        M Offline
                                        M Offline
                                        Mark_Wallace
                                        wrote on last edited by
                                        #34

                                        So are you saying that you don't want a self-driving auto?

                                        I wanna be a eunuchs developer! Pass me a bread knife!

                                        1 Reply Last reply
                                        0
                                        • D Dean Roddey

                                          So you are saying that mistakes shouldn't happen? Of course GetSomething()'s return could be changed by accident, and that would get caught also. But the more likely scenario is that someone accidentally changes the call, either by editing the wrong thing, or by search and replace, so that something besides GetSomething() is being called. Either of those things would become silent failures that could be taken care of by using an explicit type. Are they going to happen every day? No, they won't. But it's those type of silent errors that are the killers. Those are the ones that suddenly six months later the code stops working in the field and no one understands why.

                                          Explorans limites defectum

                                          R Offline
                                          R Offline
                                          Rick Shaub
                                          wrote on last edited by
                                          #35

                                          I don’t believe a useful language feature is “bad” if it doesn’t catch edge cases that are the result of not following SOLID principles.

                                          D 1 Reply Last reply
                                          0
                                          Reply
                                          • Reply as topic
                                          Log in to reply
                                          • Oldest to Newest
                                          • Newest to Oldest
                                          • Most Votes


                                          • Login

                                          • Don't have an account? Register

                                          • Login or register to search.
                                          • First post
                                            Last post
                                          0
                                          • Categories
                                          • Recent
                                          • Tags
                                          • Popular
                                          • World
                                          • Users
                                          • Groups