const 指针(与指向 const 对象的指针相反)有什么用?

发布于 2024-07-07 18:45:03 字数 297 浏览 10 评论 0原文

我经常使用指向 const 对象的指针,就像这样......

const int *p;

这仅仅意味着您无法通过 p 更改 p 指向的整数。 但我也看到过对 const 指针的引用,声明如下...

int* const p;

据我了解,这意味着指针变量本身是常量 - 您可以随时更改它指向的整数很长,但你不能让它指向其他东西。

那有什么可能的用处呢?

I've often used pointers to const objects, like so...

const int *p;

That simply means that you can't change the integer that p is pointing at through p. But I've also seen reference to const pointers, declared like this...

int* const p;

As I understand it, that means that the pointer variable itself is constant -- you can change the integer it points at all day long, but you can't make it point at something else.

What possible use would that have?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(11

混浊又暗下来 2024-07-14 18:45:03

当您为嵌入式系统设计 C 程序或需要引用相同内存(共享内存的多处理器应用程序)的特殊用途程序时,您需要常量指针。

例如,我有一个 32 位 MIP 处理器,它有一个 小液晶显示屏连接到它。 我必须将 LCD 数据写入内存中的特定端口,然后将其发送到 LCD 控制器。

我可以 #define 该数字,但随后我还必须将其转换为指针,而当我这样做时,C 编译器没有那么多选项。

此外,我可能需要它是易失性的,也可以进行强制转换,但使用提供的语法更容易、更清晰——指向易失性内存位置的常量指针。

对于 PC 程序,一个例子是:如果您设计 DOS VGA 游戏(网上有一些教程,学习基本的低级图形很有趣),那么您需要写入 VGA 内存,这可能会被引用为偏移量来自 const 指针。

When you're designing C programs for embedded systems, or special purpose programs that need to refer to the same memory (multi-processor applications sharing memory) then you need constant pointers.

For instance, I have a 32 bit MIPs processor that has a little LCD attached to it. I have to write my LCD data to a specific port in memory, which then gets sent to the LCD controller.

I could #define that number, but then I also have to cast it as a pointer, and the C compiler doesn't have as many options when I do that.

Further, I might need it to be volatile, which can also be cast, but it's easier and clearer to use the syntax provided - a const pointer to a volatile memory location.

For PC programs, an example would be: If you design DOS VGA games (there are tutorials online which are fun to go through to learn basic low level graphics) then you need to write to the VGA memory, which might be referenced as an offset from a const pointer.

誰ツ都不明白 2024-07-14 18:45:03

它允许您保护指针不被更改。 这意味着您可以保护基于指针永不更改或无意修改所做的假设,例如:

int* const p = &i;

...

p++;     /* Compiler error, oops you meant */
(*p)++;  /* Increment the number */

It allows you to protect the pointer from being changed. This means you can protect assumptions you make based on the pointer never changing or from unintentional modification, for example:

int* const p = &i;

...

p++;     /* Compiler error, oops you meant */
(*p)++;  /* Increment the number */
皓月长歌 2024-07-14 18:45:03

另一个例子:
如果您知道它是在哪里初始化的,则可以避免将来的 NULL 检查。
编译器向您保证指针永远不会改变(为 NULL)...

another example:
if you know where it was initialized, you can avoid future NULL checks.
The compiler guarantees you that the pointer never changed (to NULL)…

随遇而安 2024-07-14 18:45:03

在任何非常量 C++ 成员函数中,this 指针的类型为 C * const,其中 C 是类类型 - 您可以更改它指向的内容(即其成员),但不能将其更改为指向 C 的不同实例。 对于 const 成员函数,this 的类型为 const C * const。 还有(很少遇到)易失性const 易失性成员函数,其中this也有易失性限定符。

In any non-const C++ member function, the this pointer is of type C * const, where C is the class type -- you can change what it points to (i.e. its members), but you can't change it to point to a different instance of a C. For const member functions, this is of type const C * const. There are also (rarely encountered) volatile and const volatile member functions, for which this also has the volatile qualifier.

夜灵血窟げ 2024-07-14 18:45:03

一种用途是在低级(设备驱动程序或嵌入式)代码中,您需要引用映射到输入/输出设备(如硬件引脚)的特定地址。 某些语言允许您链接特定地址处的变量(例如,Ada 有 use at)。 在 C 中,最惯用的方法是声明一个常量指针。 请注意,此类用法还应该具有 易失性 限定符。

其他时候,这只是防御性编码。 如果您有一个不应该更改的指针,明智的做法是声明它不能更改。 这将允许编译器(和 lint 工具)检测到修改它的错误尝试。

One use is in low-level (device driver or embedded) code where you need to reference a specific address that's mapped to an input/output device like a hardware pin. Some languages allow you to link variables at specific addresses (e.g. Ada has use at). In C the most idiomatic way to do this is to declare a constant pointer. Note that such usages should also have the volatile qualifier.

Other times it's just defensive coding. If you have a pointer that shouldn't change it's wise to declare it such that it cannot change. This will allow the compiler (and lint tools) to detect erroneous attempts to modify it.

冧九 2024-07-14 18:45:03

当我想避免对指针的意外修改(例如指针算术或函数内部)时,我总是使用它们。 您还可以将它们用于单例模式。

“this”是一个硬编码的常量指针。

I've always used them when I wanted to avoid unintended modification to the pointer (such as pointer arithmetic, or inside a function). You can also use them for Singleton patterns.

'this' is a hardcoded constant pointer.

2024-07-14 18:45:03

与“const int”相同......如果编译器知道它不会改变,则可以基于此进行优化假设。

struct MyClass
{
    char* const ptr;
    MyClass(char* str) :ptr(str) {}

    void SomeFunc(MyOtherClass moc)
    {
         for(int i=0; i < 100; ++i)
         { 
                 printf("%c", ptr[i]);
                 moc.SomeOtherFunc(this);
         }
    }
}

现在,编译器可以做很多事情来优化该循环——只要它知道 SomeOtherFunc() 不会更改 ptr 的值。 有了 const,编译器就知道这一点,并且可以做出假设。 如果没有它,编译器必须假设 SomeOtherFunc 将更改 ptr。

Same as a "const int" ... if the compiler knows it's not going to change, it can be optimization assumptions based on that.

struct MyClass
{
    char* const ptr;
    MyClass(char* str) :ptr(str) {}

    void SomeFunc(MyOtherClass moc)
    {
         for(int i=0; i < 100; ++i)
         { 
                 printf("%c", ptr[i]);
                 moc.SomeOtherFunc(this);
         }
    }
}

Now, the compiler could do quite a bit to optimize that loop --- provided it knows that SomeOtherFunc() does not change the value of ptr. With the const, the compiler knows that, and can make the assumptions. Without it, the compiler has to assume that SomeOtherFunc will change ptr.

你曾走过我的故事 2024-07-14 18:45:03

我见过一些 OLE 代码,其中有一个从代码外部传入的对象,要使用它,您必须访问它传入的特定内存。因此,我们使用 const 指针来确保函数始终操纵这些值比通过 OLE 接口进来。

I have seen some OLE code where you there was an object passed in from outside the code and to work with it, you had to access the specific memory that it passed in. So we used const pointers to make sure that functions always manipulated the values than came in through the OLE interface.

灯角 2024-07-14 18:45:03

已经给出了几个很好的理由作为这个问题的答案(内存映射设备和简单的旧防御编码),但我愿意打赌,在大多数情况下,您看到这实际上是一个错误,并且意图是to item 是一个指向 const 的指针。

我当然没有数据支持这种预感,但我仍然会下注。

Several good reasons have been given as answers to this questions (memory-mapped devices and just plain old defensive coding), but I'd be willing to bet that most instances where you see this it's actually an error and that the intent was to have to item be a pointer-to-const.

I certainly have no data to back up this hunch, but I'd still make the bet.

生生不灭 2024-07-14 18:45:03

type*const type* 视为类型本身。 然后,您就会明白为什么您可能想要拥有这些类型的常量。

Think of type* and const type* as types themselves. Then, you can see why you might want to have a const of those types.

不交电费瞎发啥光 2024-07-14 18:45:03

始终将指针视为 int。 这意味着

object* var;

实际上可以这样认为

int var;

,const 指针仅仅意味着:

const object* var;

变成

const int var;

,因此你也不能更改指针指向的地址,仅此而已。 为了防止数据更改,必须将其设为指向 const 对象的指针。

always think of a pointer as an int. this means that

object* var;

actually can be thought of as

int var;

so, a const pointer simply means that:

const object* var;

becomes

const int var;

and hence u can't change the address that the pointer points too, and thats all. To prevent data change, u must make it a pointer to a const object.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文