Double const declaration

后端 未结 8 1490
花落未央
花落未央 2021-02-05 13:20

I often see the following function declaration:

some_func(const unsigned char * const buffer)
{

}

Any idea why the const is repeated before th

相关标签:
8条回答
  • 2021-02-05 13:25

    assuming const unsigned char * const

    Everyone is correct that its a const pointer to a const unsigned char.

    C++ types read mostly right to left unless there are any modifiers on the far left then these read left to right.

    0 讨论(0)
  • 2021-02-05 13:30

    This makes it a const pointer to a const value, rather than a mutable pointer to a const value or a const pointer to a mutable value.

    0 讨论(0)
  • 2021-02-05 13:33

    const * unsigned char const buffer means that you cannot modify the pointer buffer nor the memory that buffer points to.

    0 讨论(0)
  • 2021-02-05 13:36

    In a declaration like const * const T, the first const (before the *) means that what the pointer points at is const (i.e. it's a pointer to a const T). The const after the * means that the pointer itself is const (i.e. can't be modified to point at anything else).

    You can read the declaration from the object being declared outward, so const unsigned char * const buffer is read as: "buffer is a const pointer to a const unsigned char" (this is why const should always being placed after what it modifies--with it before, you have to rearrange things to make the sentence--with it declared as unsigned char const * const buffer, translation to English is simple and straighforward (or perhaps "straightbackward", since you actually read from right to left in this case).

    0 讨论(0)
  • 2021-02-05 13:37

    type declarations should(?) be read RTL. const modifies the thing on its left, but the rule is complicated by the fact that you can write both const T and T const (they mean the same thing).

    • T * const is a constant pointer to mutable T
    • T & const would be constant reference to mutable T, except references are constant by definition
    • T const * is a mutable pointer to constant T
    • T const & is a reference to constant T
    • T const * const is constant pointer to constant T
    0 讨论(0)
  • 2021-02-05 13:44

    A couple of articles to help you understand const correctness in C++:

    • Wikipedia
    • Possibility.com
    0 讨论(0)
提交回复
热议问题