is const (c++) optional?

前端 未结 11 632
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-11 21:06

according to some tutorials i read a while back, the \"const\" declaration makes a variable \"constant\" ie it cannot change later.
But i find this con

相关标签:
11条回答
  • 2020-12-11 21:13

    You lose some useful language features without const, especially regarding references. Consider:

    void f(const MyClass& m);
    void f(const int& i);
    
    // ...
    
    f(MyClass()); // OK, can pass temporary as const reference
    f(5); // OK as well, 5 is a temporary int
    

    If you consider the 'const' optional and get rid of it:

    void f(MyClass& m);
    void f(int& i);
    
    // ...
    
    f(MyClass()); // Error, cannot pass temporary as non-const reference
    f(5); // Error, same as above
    
    0 讨论(0)
  • 2020-12-11 21:14

    To answer your question first:

    Yes, you can. But only if you are careful, and everyone else who uses your code from now to eternity is also careful.

    So, on balance you are better off thinking about why you should make something const and when you should not.

    Another technique for exploring why const makes a difference is to try to make everything const at first until you have valid reasons to change something, then, and only then, remove the minimum number of consts until it works again.

    Glad to see you are thinking about the issue - its more than most do.

    0 讨论(0)
  • 2020-12-11 21:16

    In C++, "const" can a apply to a variable (making it unchangeable) or a function (rendering it unable to change other things).

    My use of "const" is not just to prevent my code from changing my variable. It's to prevent some idiot's code from changing my variable (especially if the idiot is me six months from now) and to prevent my code from changing a critical variable some idiot left exposed (especially if the idiot was me six months ago).

    0 讨论(0)
  • 2020-12-11 21:16

    Changing things that shouldn't be changed is one of the most common sources of error. It is therefore worthwhile specifying const because it prevents you from doing something wrong. Why would you want to give that up?

    const double PI = 3.14159265358979;
    
    PI=4; // generates a compiler error (good)
    

    There are some problems with the c++ notation, because a constant can only be initialized, not assigned the first time, and sometimes, you don't have the value at initialization time.

    class A {
    private:
      const int num;
    public:
      A(int x, int y) : num(0) { // oops, I don't yet know what num should be
        while ( ... ) {
    
        }
        num = ...;
      }
    };
    

    The way out of this one is to define a private function that computes the value of num but sometimes that means that instead of one clean block of code in the constructor, you are forced to split it into sections in awkward ways, just so you can initialize the variable.

    class A {
    private:
      const int num;
      int computeNum(int x, int y) { ... }
    public:
      A(int x, int y) : num(f(x,y)) {
      }
    };
    

    Sometimes, you have a value that is generally supposed to be const, but you want to selectively override that when it semantically makes sense. For example, social security numbers don't change, unless your identity is stolen. So you have just one method, called createNewSSN() which changes the otherwise constant ssn

    class Person {
    private:
      const int ssn;
    public:
      Person(int ssn_) : ssn(ssn_) {}
    
      void createNewSSN(int newssn) {
        log << "Changed SSN: " << ssn << " to " << newssn << "\n";
        *(int*)&ssn = newssn; // trust me, this is a special case....
      }
    };
    
    0 讨论(0)
  • 2020-12-11 21:19

    If you are careful, yes. But it is human to err. Also, you do not give the compiler the opportunity to optimize around these constants.

    The error message that you get is because you try to alter a const int. Simply assigning the value to a (non-const) int, you alter it as you want to.

    Const helps you, try to sprinkle more of it around and listen to the compiler. That will help you produce better code.

    0 讨论(0)
  • 2020-12-11 21:19

    Its always optional. If its all your code sure you can forget it ( I wouldn't recommend it, because it protects you), but when you interact with others, you're essentially providing a contract for them that you won't change their object or calling a function does not change the state of your object. This can be invaluable when you are not familiar with other's code, or you don't have the source.

    0 讨论(0)
提交回复
热议问题