const and non-const variables

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Filipe Sousa

    const and non-const variables

    Hi!

    I always see code written like this:

    void foo()
    {
    int b = bar();
    int g = goo();
    // k and g is never changed
    //...
    }

    instead of using const

    void foo()
    {
    const int b = bar();
    const int g = goo();
    // k and g is never changed
    //...
    }

    IMO we should use const whenever is possible or am I wrong?

    class Foo {
    std::string var;
    public:
    //...
    const std::string& get_var() const { return var; }
    }

    Foo f;
    what should I use?
    this:
    const std::string s = f.var()
    or this:
    const std::string& s = f.var()
  • ketan

    #2
    Re: const and non-const variables

    Hi,

    I understand
    -> // k and g is never changed
    meant
    // b and g is never changed

    and
    -> const std::string s = f.var()
    is
    const std::string s = f.get_var()

    This might be example of taking const to extreme.

    In my view when u get reference to your private member,
    it enables any external program to modify your private memebers!!
    Which is not good...

    e.g.

    std::string modify = f.get_var() ; // /returns std::string&
    modify = std::string("ga rbage"); << -- What happens now ??)? ( not
    const )

    So it is better to return copy of ur privates.

    Long explanation
    --------------------------
    #include <string>
    #include <iostream>

    class A {
    std::string name;
    public:
    A(std::string& in): name(in) {}
    std::string& getA(void) { return name; }
    };

    int main()
    {
    std::string inStr(" this is good");
    A test(inStr);
    test.getA() = std::string(" bad bad");
    std::cout << " value " << test.getA() << std::endl;
    }
    ------------------------------
    bye
    ketan

    Comment

    • Cy Edmunds

      #3
      Re: const and non-const variables


      "Filipe Sousa" <filipe@ipb.p t> wrote in message
      news:43dd462a$0 $14996$a729d347 @news.telepac.p t...[color=blue]
      > Hi!
      >
      > I always see code written like this:
      >
      > void foo()
      > {
      > int b = bar();
      > int g = goo();
      > // k and g is never changed
      > //...
      > }
      >
      > instead of using const
      >
      > void foo()
      > {
      > const int b = bar();
      > const int g = goo();
      > // k and g is never changed
      > //...
      > }
      >
      > IMO we should use const whenever is possible or am I wrong?[/color]

      It is extremely important to be rigorously const-correct at interfaces. It
      is far less important in implementations .
      [color=blue]
      >
      > class Foo {
      > std::string var;
      > public:
      > //...
      > const std::string& get_var() const { return var; }
      > }
      >
      > Foo f;
      > what should I use?
      > this:
      > const std::string s = f.var()
      > or this:
      > const std::string& s = f.var()[/color]

      The reference version *might* be faster, but the resulting reference is
      dependent on f. Copying the string is less likely to produce hard to find
      errors when f is destroyed or modified in some other way (perhaps as a
      result of a change to the code which made by somebody else in the far
      future).


      Comment

      • Filipe Sousa

        #4
        Re: const and non-const variables

        Cy Edmunds wrote:[color=blue]
        > "Filipe Sousa" <filipe@ipb.p t> wrote in message
        > news:43dd462a$0 $14996$a729d347 @news.telepac.p t...[color=green]
        >> Hi!
        >>
        >> I always see code written like this:
        >>
        >> void foo()
        >> {
        >> int b = bar();
        >> int g = goo();
        >> // k and g is never changed
        >> //...
        >> }
        >>
        >> instead of using const
        >>
        >> void foo()
        >> {
        >> const int b = bar();
        >> const int g = goo();
        >> // k and g is never changed
        >> //...
        >> }
        >>
        >> IMO we should use const whenever is possible or am I wrong?[/color]
        >
        > It is extremely important to be rigorously const-correct at interfaces. It
        > is far less important in implementations .[/color]

        But it might be a hint to the user or the programmer when inspecting the
        source code that b and g will never change. I don't know if the compiler
        does any optimization when we use const int b instead of int b.
        [color=blue][color=green]
        >> class Foo {
        >> std::string var;
        >> public:
        >> //...
        >> const std::string& get_var() const { return var; }
        >> }
        >>
        >> Foo f;
        >> what should I use?
        >> this:
        >> const std::string s = f.var()
        >> or this:
        >> const std::string& s = f.var()[/color]
        >
        > The reference version *might* be faster, but the resulting reference is
        > dependent on f. Copying the string is less likely to produce hard to find
        > errors when f is destroyed or modified in some other way (perhaps as a
        > result of a change to the code which made by somebody else in the far
        > future).[/color]

        I understant.

        --
        Filipe Sousa

        Comment

        • Cy Edmunds

          #5
          Re: const and non-const variables


          [snip]
          [color=blue][color=green][color=darkred]
          >>>
          >>> IMO we should use const whenever is possible or am I wrong?[/color]
          >>
          >> It is extremely important to be rigorously const-correct at interfaces.
          >> It
          >> is far less important in implementations .[/color]
          >
          > But it might be a hint to the user or the programmer when inspecting the
          > source code that b and g will never change.[/color]

          OK, who is this programmer who is inspecting the implementation? If he is
          just a client of the code he is making a mistake. Any assumption he makes
          about how the function is implemented is unwarranted and dangerous. He
          should be looking at the interface and the documentation only. If he is
          actually modifying the implementation a const here and there might be of
          some help to him. Thus being const correct in the implementation has a minor
          advantage.
          [color=blue]
          > I don't know if the compiler
          > does any optimization when we use const int b instead of int b.[/color]

          This might result in some sort of minor efficiency improvement in some
          cases. Again, being const correct in the implementation has a slight
          advantage.

          The importance of const correctness at the interface is much greater. It is
          often critical to correct usage of the code by any client (not just a
          re-implementor) and may prevent gross inefficiencies such as making backups
          of large objects unneccesarily before making a call.

          [snip]


          Comment

          • Luke Meyers

            #6
            Re: const and non-const variables

            Cy Edmunds wrote:[color=blue]
            > OK, who is this programmer who is inspecting the implementation? If he is
            > just a client of the code he is making a mistake. Any assumption he makes
            > about how the function is implemented is unwarranted and dangerous. He
            > should be looking at the interface and the documentation only. If he is
            > actually modifying the implementation a const here and there might be of
            > some help to him. Thus being const correct in the implementation has a minor
            > advantage.[/color]

            What about peer review? It's easier to verify code correctness if the
            code's intentions are made explicit, and constness helps with this. I
            would consider this the primary advantage of using const within local
            implementation scopes.

            Luke

            Comment

            • Luke Meyers

              #7
              Re: const and non-const variables

              ketan wrote:[color=blue]
              > This might be example of taking const to extreme.[/color]

              I disagree. It's entirely reasonable.
              [color=blue]
              > In my view when u get reference to your private member,
              > it enables any external program to modify your private memebers!![/color]

              Uh, no, not if it's a _const_ reference. That's kind of the point.
              [color=blue]
              > std::string modify = f.get_var() ; // /returns std::string&[/color]

              No, it returns std::string const&. Which means that the copy
              constructor is invoked, since this is initialization by value.
              [color=blue]
              > modify = std::string("ga rbage"); << -- What happens now ??)? ( not
              > const )[/color]

              modify is modified, but the original string is untouched.
              [color=blue]
              > So it is better to return copy of ur privates.[/color]

              If so, you haven't demonstrated why. The only difference I can think
              of between returning by const& and returning by copy is that if the
              result is used to initialize a const&, no copy is made but the lifetime
              of the initialized reference is tied to that of the referent. Surely
              there are cases where each is appropriate.

              Luke

              Luke

              Comment

              Working...