Skip to content
  • Categories
  • Recent
  • Tags
  • Popular
  • Users
  • Groups
  • Search
  • Get Qt Extensions
  • Unsolved
Collapse
Brand Logo
  1. Home
  2. Special Interest Groups
  3. C++ Gurus
  4. How rigorous are you about using const?
Forum Updated to NodeBB v4.3 + New Features

How rigorous are you about using const?

Scheduled Pinned Locked Moved Solved C++ Gurus
34 Posts 11 Posters 5.5k Views 9 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.
  • JonBJ Offline
    JonBJ Offline
    JonB
    wrote on last edited by JonB
    #7

    OK, since we're on a roll, let's push the boat out!

    Do you bother to put const against simple value types in, say, formal parameters of a function?

    void person_function(const int age, const double weight, const bool is_female)
    {
        const int next_birthday = age + 1;
        if (! is_female)
            qDebug() << next_birthday << weight / age;
    }
    

    If so, I think I'll want a const key on my keyboard because I'm going to be typing it so often!

    K 1 Reply Last reply
    1
    • JonBJ JonB

      OK, since we're on a roll, let's push the boat out!

      Do you bother to put const against simple value types in, say, formal parameters of a function?

      void person_function(const int age, const double weight, const bool is_female)
      {
          const int next_birthday = age + 1;
          if (! is_female)
              qDebug() << next_birthday << weight / age;
      }
      

      If so, I think I'll want a const key on my keyboard because I'm going to be typing it so often!

      K Offline
      K Offline
      koahnig
      wrote on last edited by
      #8

      @JonB said in How rigorous are you about using const?:

      OK, since we're on a roll, let's push the boat out!

      Do you bother to put const against simple value types in, say, formal parameters of a function?

      void person_function(const int age, const double weight, const bool is_female)
      {
          const int next_birthday = age + 1;
          if (! is_female)
              qDebug() << next_birthday << weight / age;
      }
      

      If so, I think I'll want a const key on my keyboard because I'm going to be typing it so often!

      Personally that would be too much const here. Certainly it does not harm, but it is completely useless in the parameter list, because it is to the exterior const anyhow. I could see only some advantages for rather large routines, when you need to ensure that you are not accidentially changing the variable.

      Vote the answer(s) that helped you to solve your issue(s)

      JonBJ sierdzioS 2 Replies Last reply
      1
      • K koahnig

        @JonB said in How rigorous are you about using const?:

        OK, since we're on a roll, let's push the boat out!

        Do you bother to put const against simple value types in, say, formal parameters of a function?

        void person_function(const int age, const double weight, const bool is_female)
        {
            const int next_birthday = age + 1;
            if (! is_female)
                qDebug() << next_birthday << weight / age;
        }
        

        If so, I think I'll want a const key on my keyboard because I'm going to be typing it so often!

        Personally that would be too much const here. Certainly it does not harm, but it is completely useless in the parameter list, because it is to the exterior const anyhow. I could see only some advantages for rather large routines, when you need to ensure that you are not accidentially changing the variable.

        JonBJ Offline
        JonBJ Offline
        JonB
        wrote on last edited by JonB
        #9

        @koahnig
        Yep, that's fine by me! I just wanted to know what you C++-long-timers do/don't do :)

        1 Reply Last reply
        0
        • Chris KawaC Offline
          Chris KawaC Offline
          Chris Kawa
          Lifetime Qt Champion
          wrote on last edited by Chris Kawa
          #10

          I believe that adding const on parameters passed by value is a bit of a language design problem.
          It's a copy, so adding const in the interface of the function exposes details of internal implementation of the function - you know it won't be modified inside, but you shouldn't have to know that. If you're giving the function a copy it's not your business whether it modifies the copy or not. You're not getting it back after all. On the other hand you might want that const internally and adding it in the param declaration is the only way. So there's a bit of a problem - you don't want that const externally but you do want it internally.
          And here it gets hairy, because a little known fact about C++ is that this is perfectly valid:

          class Foo {
              void Bar(int);
          };
          
          void Foo::Bar(const int) {}
          

          so you can legally eat cake and have cake at the same time. But this is so obscure and unexpected that you don't see that done in practice. Personally I just don't use const here.

          As for const on local parameters - I use it not on some principle or for possible optimizations but for far more trivial reasons. I work on a massive code base and using const on locals is a great way to catch interface bugs.

          EDIT: Scratch that. I mixed it with another pattern :P

          K 1 Reply Last reply
          2
          • mrjjM Offline
            mrjjM Offline
            mrjj
            Lifetime Qt Champion
            wrote on last edited by
            #11

            Hi
            I never used it for temp variables or by copy parameters as the gain seems slim.
            However, const is vital for protecting data from being modified by a sub-function and
            also to clearly state in an interfaces that a function will not alter your data.

            Btw. It could be fun to develop some test cases to validate the decades old saying that const allows the
            compiler to optimize the code as we never really saw any speed gains during profiling.
            Not saying its not true, but at least with 3 different compilers for embedded development, the
            profiler showed no speed gains with const.

            1 Reply Last reply
            0
            • K koahnig

              @JonB said in How rigorous are you about using const?:

              OK, since we're on a roll, let's push the boat out!

              Do you bother to put const against simple value types in, say, formal parameters of a function?

              void person_function(const int age, const double weight, const bool is_female)
              {
                  const int next_birthday = age + 1;
                  if (! is_female)
                      qDebug() << next_birthday << weight / age;
              }
              

              If so, I think I'll want a const key on my keyboard because I'm going to be typing it so often!

              Personally that would be too much const here. Certainly it does not harm, but it is completely useless in the parameter list, because it is to the exterior const anyhow. I could see only some advantages for rather large routines, when you need to ensure that you are not accidentially changing the variable.

              sierdzioS Offline
              sierdzioS Offline
              sierdzio
              Moderators
              wrote on last edited by
              #12

              @koahnig said in How rigorous are you about using const?:

              void person_function(const int age, const double weight, const bool is_female)

              I started using const also in parameters after I joined one project where it was the convention.

              It does have some merits - when implementing a function, you do expect the input parameter to have the same value. But when it's not const, you can modify and forget that you did so, leading to bugs. But again, it's not a strong argument or a big issue.

              (Z(:^

              K 1 Reply Last reply
              0
              • Chris KawaC Chris Kawa

                I believe that adding const on parameters passed by value is a bit of a language design problem.
                It's a copy, so adding const in the interface of the function exposes details of internal implementation of the function - you know it won't be modified inside, but you shouldn't have to know that. If you're giving the function a copy it's not your business whether it modifies the copy or not. You're not getting it back after all. On the other hand you might want that const internally and adding it in the param declaration is the only way. So there's a bit of a problem - you don't want that const externally but you do want it internally.
                And here it gets hairy, because a little known fact about C++ is that this is perfectly valid:

                class Foo {
                    void Bar(int);
                };
                
                void Foo::Bar(const int) {}
                

                so you can legally eat cake and have cake at the same time. But this is so obscure and unexpected that you don't see that done in practice. Personally I just don't use const here.

                As for const on local parameters - I use it not on some principle or for possible optimizations but for far more trivial reasons. I work on a massive code base and using const on locals is a great way to catch interface bugs.

                EDIT: Scratch that. I mixed it with another pattern :P

                K Offline
                K Offline
                koahnig
                wrote on last edited by
                #13

                @Chris-Kawa said in How rigorous are you about using const?:

                I believe that adding const on parameters passed by value is a bit of a language design problem.
                It's a copy, so adding const in the interface of the function exposes details of internal implementation of the function - you know it won't be modified inside, but you shouldn't have to know that. If you're giving the function a copy it's not your business whether it modifies the copy or not. You're not getting it back after all. On the other hand you might want that const internally and adding it in the param declaration is the only way. So there's a bit of a problem - you don't want that const externally but you do want it internally.
                And here it gets hairy, because a little known fact about C++ is that this is perfectly valid:

                class Foo {
                    void Bar(int);
                };
                
                void Foo::Bar(const int) {}
                

                so you can legally eat cake and have cake at the same time. But this is so obscure and unexpected that you don't see that done in practice. Personally I just don't use const here.

                As for const on local parameters - I use it not on some principle or for possible optimizations but for far more trivial reasons. I work on a massive code base and using const on locals is a great way to catch interface bugs.

                EDIT: Scratch that. I mixed it with another pattern :P

                I would not be concerned about implementation details presented to the outside. At the day's end you could use it to stray wrong assumptions to people trying to interpret such details. If you want tohide you can and will hide implementation details. The easiest way is using a const reference to the input parameter and use the reference only. No cost after compilation to my understanding.

                Vote the answer(s) that helped you to solve your issue(s)

                1 Reply Last reply
                0
                • sierdzioS sierdzio

                  @koahnig said in How rigorous are you about using const?:

                  void person_function(const int age, const double weight, const bool is_female)

                  I started using const also in parameters after I joined one project where it was the convention.

                  It does have some merits - when implementing a function, you do expect the input parameter to have the same value. But when it's not const, you can modify and forget that you did so, leading to bugs. But again, it's not a strong argument or a big issue.

                  K Offline
                  K Offline
                  koahnig
                  wrote on last edited by
                  #14

                  @sierdzio said in How rigorous are you about using const?:

                  @koahnig said in How rigorous are you about using const?:

                  void person_function(const int age, const double weight, const bool is_female)

                  I started using const also in parameters after I joined one project where it was the convention.

                  It does have some merits - when implementing a function, you do expect the input parameter to have the same value. But when it's not const, you can modify and forget that you did so, leading to bugs. But again, it's not a strong argument or a big issue.

                  If there is a project with that rule, I would simply follow. Sometimes there is no need to have useless time-consuming fights.
                  As I have stated larger routines may have sometimes the issue, that you need to ensure to the input value to the end. However, I would not do it directly through a const in the parameter list.

                  @mrjj said in How rigorous are you about using const?:

                  Btw. It could be fun to develop some test cases to validate the decades old saying that const allows the
                  compiler to optimize the code as we never really saw any speed gains during profiling.
                  Not saying its not true, but at least with 3 different compilers for embedded development, the
                  profiler showed no speed gains with const.

                  I would be really interested to see construct where you can verify cpu consumption advantages of const. Whenever I have tried to see such advantages it always ended with cannot decide. However, that might be a compiler implementation issue.

                  Vote the answer(s) that helped you to solve your issue(s)

                  1 Reply Last reply
                  0
                  • Kent-DorfmanK Offline
                    Kent-DorfmanK Offline
                    Kent-Dorfman
                    wrote on last edited by
                    #15

                    The stench of const will permiate a class structure and make it a royal PITA to get things to compile with brain dead enhanced warnings all enabled...but that's what happens when a traditionally artistic field turns into assembly line work governed by poor programmers who feel they need to stifle true creativity with "safety rules" to given them some feeling of control over things they really don't understand.

                    When C++ was very Cish and I could treat memory as I saw fit, but had some nice OO additions, I liked it...Modern C++ (especially in commercial environments) is more of a SCRUM boondoggle where you spend more time documenting why you cannot do something than actually solving programming problems with creative and elegant solutions....I really need to retire.

                    Chris KawaC 1 Reply Last reply
                    0
                    • Kent-DorfmanK Kent-Dorfman

                      The stench of const will permiate a class structure and make it a royal PITA to get things to compile with brain dead enhanced warnings all enabled...but that's what happens when a traditionally artistic field turns into assembly line work governed by poor programmers who feel they need to stifle true creativity with "safety rules" to given them some feeling of control over things they really don't understand.

                      When C++ was very Cish and I could treat memory as I saw fit, but had some nice OO additions, I liked it...Modern C++ (especially in commercial environments) is more of a SCRUM boondoggle where you spend more time documenting why you cannot do something than actually solving programming problems with creative and elegant solutions....I really need to retire.

                      Chris KawaC Offline
                      Chris KawaC Offline
                      Chris Kawa
                      Lifetime Qt Champion
                      wrote on last edited by
                      #16

                      @Kent-Dorfman:

                      but that's what happens when a traditionally artistic field turns into assembly line work governed by poor programmers

                      You seem angry :) Const was not invented as a tool to keep poor programmers in check. It was introduced by quite smart people that recognized reoccurring problems of mutability in ever growing code bases. When you work with multi-million line project it's simply impossible to hold every dependency and restriction in your head and immutability is a great tool to help with that. There's nothing mandatory about it. Like any other tool you use it as you see fit, but it's been demonstrated time and again that restricting mutability of the system lifts its quality quite a lot. If it were up to me I'd make const the default and only declare mutable things that I know need to change (just with a shorter keyword than mutable maybe).

                      @Kent-Dorfman:

                      When C++ was very Cish and I could treat memory as I saw fit, but had some nice OO additions, I liked it

                      Nothing changed in that regard in C++. You can still play with bits, bytes, alignment, paging etc. There are more restrictions for memory access these days but they are imposed on the OS level, not language level and that's mostly because malware and internet. I'm sure it's obvious to you that exposing entire raw memory to a small utility in a server cluster or to any program in an ever online world is a bad idea.

                      @Kent-Dorfman:

                      Modern C++ (especially in commercial environments) is more of a SCRUM boondoggle

                      Maybe you just picked the wrong project then? They are not all the same. The one I'm working on at least sure doesn't feel like that. And we don't use SCRUM :)

                      @Kent-Dorfman:

                      I really need to retire.

                      Or just a break to recharge your batteries and a project that better fits your liking? Cheer up. It's not all doom and gloom ;)

                      1 Reply Last reply
                      3
                      • mrjjM Offline
                        mrjjM Offline
                        mrjj
                        Lifetime Qt Champion
                        wrote on last edited by
                        #17

                        @Chris-Kawa said i

                        If it were up to me I'd make const the default and only declare mutable things that I know need to change (just with a shorter keyword than mutable maybe).

                        This i wanted of for decades. It would break a lot of code but if it was a compile flag/opt in then it could work.

                        So please run for c++ committee,so i can vote for you 😋

                        Chris KawaC sierdzioS 2 Replies Last reply
                        2
                        • mrjjM mrjj

                          @Chris-Kawa said i

                          If it were up to me I'd make const the default and only declare mutable things that I know need to change (just with a shorter keyword than mutable maybe).

                          This i wanted of for decades. It would break a lot of code but if it was a compile flag/opt in then it could work.

                          So please run for c++ committee,so i can vote for you 😋

                          Chris KawaC Offline
                          Chris KawaC Offline
                          Chris Kawa
                          Lifetime Qt Champion
                          wrote on last edited by
                          #18

                          @mrjj said:

                          This i wanted of for decades. It would break a lot of code but if it was a compile flag/opt in then it could work.
                          So please run for c++ committee,so i can vote for you

                          Haha, thanks, but it's just not gonna happen in C++. It's far too late and adding it even as an option would just ugly split the community. Imagine you have a large project which uses it and want to use a small utility library that doesn't They're incompatible on interface level. Bummer.

                          mrjjM 1 Reply Last reply
                          0
                          • Chris KawaC Chris Kawa

                            @mrjj said:

                            This i wanted of for decades. It would break a lot of code but if it was a compile flag/opt in then it could work.
                            So please run for c++ committee,so i can vote for you

                            Haha, thanks, but it's just not gonna happen in C++. It's far too late and adding it even as an option would just ugly split the community. Imagine you have a large project which uses it and want to use a small utility library that doesn't They're incompatible on interface level. Bummer.

                            mrjjM Offline
                            mrjjM Offline
                            mrjj
                            Lifetime Qt Champion
                            wrote on last edited by
                            #19

                            @Chris-Kawa
                            Hehe yeah i know in practice it would be hard to manage but on the other hand, we survived
                            years of template hell where you were never sure if the compiler would support it and still today
                            c++ is not a uniform thing between compiler vendors even it has become much better.

                            So i still think it would be great for new projects and 5 years later many of the lib you would use, would be compilable with this on.

                            But yeah its a 99% pipe dream.

                            1 Reply Last reply
                            0
                            • mrjjM mrjj

                              @Chris-Kawa said i

                              If it were up to me I'd make const the default and only declare mutable things that I know need to change (just with a shorter keyword than mutable maybe).

                              This i wanted of for decades. It would break a lot of code but if it was a compile flag/opt in then it could work.

                              So please run for c++ committee,so i can vote for you 😋

                              sierdzioS Offline
                              sierdzioS Offline
                              sierdzio
                              Moderators
                              wrote on last edited by
                              #20

                              @mrjj said in How rigorous are you about using const?:

                              @Chris-Kawa said i

                              If it were up to me I'd make const the default and only declare mutable things that I know need to change (just with a shorter keyword than mutable maybe).

                              This i wanted of for decades. It would break a lot of code but if it was a compile flag/opt in then it could work.

                              So please run for c++ committee,so i can vote for you 😋

                              Oh, +1 to that :D

                              (Z(:^

                              1 Reply Last reply
                              0
                              • Kent-DorfmanK Offline
                                Kent-DorfmanK Offline
                                Kent-Dorfman
                                wrote on last edited by
                                #21

                                @Chris-Kawa Look man, I've been coding since the days of Fortran-4 and have forgotten more languages than typical programmers even know exist. I was brought up in a generation where you turned 12 and you found a 22lr under the christmas tree, and your dad simply said, "don't hurt anyone". In short, we didn't have all these ridiculous, hard to swallow rules designed to "protect us from ourselves", and because management didn't trust us...As was said in "real programmers don't use Pascal" "real programmers don't like WYSIWYG. We want you asked for it, you got." And I'm always going to challenge those blanket statements about obscure studies and cases that "have proven time and time again" a particular point of view. More often than not they are simple dogma to support a persons particular religion. So yeah, maybe I can tune a compiler with flags to get behaviour that doesn't rub me raw...but...it sure as hades ain't gonna fly with the code nazis who are 1) half my age, 2) were poor programmers so they ended up being leads, 3) are on a quest to lower everyone to a least common denominator, and 4) are a big part of the mission to make "process" more important than "product"...becuase they don't really understand the product and feel empowered by introducing process instead.

                                Angry? Well, very jaded, to say the least...Until you've been a 50 yo programmer who had a 33yo lead tell you he was going to "teach you to program" because he didn't want to look at a piece of code and be able to tell who wrote it out of a team of five...well, our experiences are probably very different.

                                Anyway, I digres...forgive the rant.

                                Chris KawaC 1 Reply Last reply
                                1
                                • Kent-DorfmanK Kent-Dorfman

                                  @Chris-Kawa Look man, I've been coding since the days of Fortran-4 and have forgotten more languages than typical programmers even know exist. I was brought up in a generation where you turned 12 and you found a 22lr under the christmas tree, and your dad simply said, "don't hurt anyone". In short, we didn't have all these ridiculous, hard to swallow rules designed to "protect us from ourselves", and because management didn't trust us...As was said in "real programmers don't use Pascal" "real programmers don't like WYSIWYG. We want you asked for it, you got." And I'm always going to challenge those blanket statements about obscure studies and cases that "have proven time and time again" a particular point of view. More often than not they are simple dogma to support a persons particular religion. So yeah, maybe I can tune a compiler with flags to get behaviour that doesn't rub me raw...but...it sure as hades ain't gonna fly with the code nazis who are 1) half my age, 2) were poor programmers so they ended up being leads, 3) are on a quest to lower everyone to a least common denominator, and 4) are a big part of the mission to make "process" more important than "product"...becuase they don't really understand the product and feel empowered by introducing process instead.

                                  Angry? Well, very jaded, to say the least...Until you've been a 50 yo programmer who had a 33yo lead tell you he was going to "teach you to program" because he didn't want to look at a piece of code and be able to tell who wrote it out of a team of five...well, our experiences are probably very different.

                                  Anyway, I digres...forgive the rant.

                                  Chris KawaC Offline
                                  Chris KawaC Offline
                                  Chris Kawa
                                  Lifetime Qt Champion
                                  wrote on last edited by
                                  #22

                                  @Kent-Dorfman said:

                                  Anyway, I digres...forgive the rant.

                                  No problem. I can see where you come from. The longer you're in the more stuff accumulates and it's good to let some of it out from time to time. We're here for (and with) you ;)

                                  Until you've been a 50 yo programmer who had a 33yo lead tell you he was going to "teach you to program" because he didn't want to look at a piece of code and be able to tell who wrote it out of a team of five...well, our experiences are probably very different.

                                  Not by much, but yeah and I'm sorry to hear that yours is like this. I can only again tell you it's not everywhere like that.

                                  Where I'm at I get along with people both twice and half my age. Actually I'm often the guy that tries to make those two groups talk to each other, because, from what I've seen, that's when magic truly happens :) With the older gen we do have a relation where I can maybe hint them that they don't have to copy paste that function 30 times if they just use a simplest template and I get to see some cool low level tricks they developed over the years to pass along to the younger staff. It can be really synergetic if you let it. It's only "us vs them" if you all make it so. With the younglings it's similar. Sure, you can meet some arogant a-holes thinking they know everything because they followed a tutorial on youtube, but you either whack some sense into them or just part ways. They will learn eventually or they won't and go become a manager at another company ;) That's just how the industry rolls. You can get grumpy about the system or learn to live within it and shape it from the inside.

                                  I mean look at it from the perspective of a fresh fish in the pond. Here you come, sure of yourself, full of enthusiasm and there along shows up this whiny grandpa that says everything you do is wrong and that's not how it was done in his days... It doesn't matter that you're right. You're not gonna have a very good working relation this way and you won't pass any of the knowledge you undoubtedly amassed over the years. To make someone learn you first need them to listen and for that to happen they must either like you, or at least tolerate you. The best way to make someone change their ways is to make them believe they came up with it themselves, not by hammering into them that their way is bad. Works wonders with some clueless management in my experience ;) I particularly like the trick of giving them two options, one of which is so bad they can't possibly choose it so you get your way and them being proud of themselves when it turns out ok. Win win :)

                                  And I'm always going to challenge those blanket statements about obscure studies and cases that "have proven time and time again" a particular point of view.

                                  Fair enough. That's something I really like in people and I do try to avoid empty words not backed up by some data. It's just not always feasible to tie in actual scientific articles and lengthy study summaries into ad hoc discussions like this. I'll try to be more rigorous about that though. Thanks for pointing that out.

                                  In short, we didn't have all these ridiculous, hard to swallow rules designed to "protect us from ourselves", and because management didn't trust us

                                  Yeah, sure, but I think you're projecting a bit too much. Not every language feature after early C is like that. const is very much not so and was introduced by the old timers like you actually to improve. It was widely adopted into other languages ever since because it's just a really useful feature, not because some knowitall said so.

                                  1. are a big part of the mission to make "process" more important than "product"...becuase they don't really understand the product and feel empowered by introducing process instead.

                                  Yeah, I share the sentiment. There are people like that, but what are you gonna do? There's almost 8b people on the planet. You're gonna meet some of those no matter what. I met a person somewhat like that once. First I tried to work with them, then work around them and when that didn't work I just changed jobs. Turns out best decision in my career ;)

                                  1 Reply Last reply
                                  2
                                  • S Offline
                                    S Offline
                                    SimonSchroeder
                                    wrote on last edited by
                                    #23

                                    Answering the original question, I am a little inconsistent in the use of const. At one point I tried to use it everywhere for local variables. (It never occured to me to use it on arguments as well, except for the obvious const ref, e.g. const std::string &str). Currently, I am using const a lot less because I am working on an older project where member functions are rarely const. I don't see much help in this case.

                                    In general, I would advocate the use of const. It should make your intent clearer. If done right, const-methods only should return const objects (copy, const-ref, or const pointer). This automatically means that you need to declare your local temporary variables const in many places. With modern C++ you could use auto instead. Though even then I prefer const auto or even const auto & instead of plain auto. To be honest, I discourage the use of auto in these cases (going against the mantra of Herb Sutter et al.). Using the example of the OP:

                                    QWidget *widg = otherClass->someMethod(abc, def);
                                    

                                    is IMHO a lot better than

                                    auto widg = otherClass->someMethod(abc, def);
                                    

                                    as the former states that we are expecting a QWidget. The strongest point about C++ is that it has static typing which helps to find a lot of errors at compile time. We need to give the compiler as much information as possible to help us catch these kind of errors. This means using QWidget instead of auto in the example and it means using const everywhere if possible.

                                    The major point about using const everywhere is about future-proofing your software. There are many statements that const means thread-safe, or at least should mean thread-safe. The standards committee is strongly pushing in this direction. If you are careful in the use and implementation of const in your classes, a consistent use of const sets you up for using multi-threading in your software in the future.

                                    Lastly, I want to talk about performance. I don't have any numbers, but it is more like my collected wisdom from many years of curiosity. It is my current understanding of this complex topic, but please do correct me if you know I am wrong. First of all, I think that compilers are very smart nowadays. In many cases I expect compilers to figure out if some local variable is changed during its lifetime. Especially for built-in types this would not really make a performance difference (at least when turning on at least some optimizations). Just maybe there are very few additional optimizations a compiler can do if you declare integer or floating point numbers as const, but I wouldn't hold my breath for it. For user defined types it is certainly a different story what the compiler is able to figure out on its own. Providing const members at all is certainly necessary, but I am not sure if compilers really do assume that const methods do not change the object and do optimizations accordingly. It certainly can make a difference when having overloaded const- and non-const-members. What comes to mind is operator[](int) and operator[](int) const of std::vector and other vector classes, like QVector. For small types, like int and double, the const version can return a copy of the value. I remember vagely that for some vector class the implementation of the non-const version is required to return a separate reference type to support all features. This means an actual separate object that behaves like the contained type of the vector, but actually is a wrapper class only referencing the actual object. For these special cases performance can be different. Nobody should remember these corner cases, but instead use const whenever possible. For me, writing scientific software, this is especially crucial for matrix classes where you might acces just a single row or column or even indexing a single element.

                                    Reading through previous answers, there are two things I never really thought about: 1. I never really thought about using const for arguments. 2. I have never really thought about their use with pointers. Going back to the example:

                                    QWidget *widg = otherClass->someMethod(abc, def);
                                    

                                    In general, I would introduce const like this:

                                    const QWidget *widg = otherClass->someMethod(abc, def);
                                    

                                    Now, that I think about it I notice that this only makes only the QWidget object const (which helps to catch the most common errors associated with const). Especially in the context of the local temporary variable the pointer itself is also const in common use cases. This begs the question how to write it:

                                    const QWidget *const widg = otherClass->someMethod(abc, def);
                                    

                                    or

                                    QWidget const *const widg = otherClass->someMethod(abc, def);
                                    

                                    Which variant do you prefer? (These two versions are really equivalent to the compiler.) If we were to agree on the rule "use const everywhere", should this include making the pointer const as well or would just const QWidget *widg be enough?

                                    1 Reply Last reply
                                    1
                                    • Chris KawaC Offline
                                      Chris KawaC Offline
                                      Chris Kawa
                                      Lifetime Qt Champion
                                      wrote on last edited by
                                      #24

                                      @SimonSchroeder said:

                                      In many cases I expect compilers to figure out if some local variable is changed during its lifetime.

                                      I think it was at some cpp con few years back that one of the implementers of LLVM said blatantly that they just straight ignore const in most of the optimizer passes. That's mostly because const_cast exists and any optimizations they might think of have some corner case that generates hard to diagnose or debug casting problems so it's just not worth it. Also you can't assume anything about a variable that crosses object file boundaries, unless you use something like WPO, but I don't think anyone is really optimizing for const beyond maybe some basic stuff.

                                      What comes to mind is operator and operator const of std::vector and other vector classes, like QVector

                                      I don't think it matters for std:: but with Qt containers const is important because of implicit sharing. non-const methods cause a detach that can be costly in many cases.

                                      This begs the question how to write it:

                                      IMO it's a pointless debate about east const vs west const. There are endless arguments that it should read right to left or like spoken word. Should programming languages read like books or shouldn't? Outside to inside or inside to outside? It should stay with type or with the indirection character. All of that just boils down to personal preference I think. I use west const just because that's how I learned it and most projects I worked in used it that way but I don't have any strong opinion either way. I don't care which is used, but the thing that actually bugs me is that there are two ways to use it. It's just unnecessary and I'd prefer much more to have only one valid syntax for it (whichever it is) because all that choice does is confuse the hell out of people, especially fresh C++ers.

                                      S 1 Reply Last reply
                                      1
                                      • sierdzioS Offline
                                        sierdzioS Offline
                                        sierdzio
                                        Moderators
                                        wrote on last edited by
                                        #25

                                        That's one place where a simple new keyword could clarify a lot and make code more readable on first sight: const_object (or const_pointee or whatever).

                                        const_object QWidget *blah; // Object is const, pointer is not
                                        const QWidget *blah; // Pointer is const, object is not
                                        const const_object QWidget *blah; // Both are const. For clarity, const_pointer could be added, too
                                        

                                        I don't think anybody cares for it enough to change suggest it. C++ was always proud of it's hard to read syntax ;-)

                                        (Z(:^

                                        Chris KawaC kshegunovK 2 Replies Last reply
                                        1
                                        • sierdzioS sierdzio

                                          That's one place where a simple new keyword could clarify a lot and make code more readable on first sight: const_object (or const_pointee or whatever).

                                          const_object QWidget *blah; // Object is const, pointer is not
                                          const QWidget *blah; // Pointer is const, object is not
                                          const const_object QWidget *blah; // Both are const. For clarity, const_pointer could be added, too
                                          

                                          I don't think anybody cares for it enough to change suggest it. C++ was always proud of it's hard to read syntax ;-)

                                          Chris KawaC Offline
                                          Chris KawaC Offline
                                          Chris Kawa
                                          Lifetime Qt Champion
                                          wrote on last edited by
                                          #26

                                          @sierdzio The committee is usually very reluctant to add new keywords, especially if they're just sugar and I must admit I agree with them on this one. I really don't want to write constexpr const const_object Foo* const_pointer const if I don't have to :P

                                          J.HilkJ 1 Reply Last reply
                                          4

                                          • Login

                                          • Login or register to search.
                                          • First post
                                            Last post
                                          0
                                          • Categories
                                          • Recent
                                          • Tags
                                          • Popular
                                          • Users
                                          • Groups
                                          • Search
                                          • Get Qt Extensions
                                          • Unsolved