Top-level const doesn't influence a function signature

后端 未结 7 2018
悲哀的现实
悲哀的现实 2020-11-27 08:32

From the C++ Primer 5th Edition, it says:

int f(int){ /* can write to parameter */}
int f(const int){ /* cannot write to parameter */}

The

7条回答
  •  失恋的感觉
    2020-11-27 08:44

    Since there is no difference to the caller, and no clear way to distinguish between a call to a function with a top level const parameter and one without, the language rules ignore top level consts. This means that these two

    void foo(const int);
    void foo(int);
    

    are treated as the same declaration. If you were to provide two implementations, you would get a multiple definition error.

    There is a difference in a function definition with top level const. In one, you can modify your copy of the parameter. In the other, you can't. You can see it as an implementation detail. To the caller, there is no difference.

    // declarations
    void foo(int);
    void bar(int);
    
    // definitions
    void foo(int n)
    {
      n++;
      std::cout << n << std::endl;
    }
    
    void bar(const int n)
    {
      n++; // ERROR!
      std::cout << n << std::endl;
    }
    

    This is analogous to the following:

    void foo()
    {
      int = 42;
      n++;
      std::cout << n << std::endl;
    }
    
    void bar()
    {
      const int n = 42;
      n++; // ERROR!
      std::cout << n << std::endl;
    }
    

提交回复
热议问题