当原始数据为const时,是否要修改指针所指向的UB? [英] Is it UB to Modify where pointer points, when original data is const?

查看:56
本文介绍了当原始数据为const时,是否要修改指针所指向的UB?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在指针的数据为const时更改指针指向的位置是否为未定义行为?示例:

Would it be undefined behavior to change where a pointer points, when its data is const? Example:

const char* p = "foo";
p = "boo";

我相信这不是UB,因为指针本身不是const并且我没有修改 foo 对象。

I believe that this is not UB, because the pointer itself is not const and I'm not modifying the "foo" object.

额外的问题:并且不更改const指针的const数据吗?会UB吗?示例:

Extra question: and altering not const data of a const pointer? Would be UB? Example:

char* const p = "foo";
(*(char**)&p) = (char*)malloc(strlen(p));


推荐答案


我相信不是UB,因为指针本身不是const,并且我没有修改 foo对象。

I believe that this is not UB, because the pointer itself is not const and I'm not modifying the "foo" object.

这是正确的。指针不是 const ,因此您可以根据需要将其更改为指向其他内容。在这种情况下,它不会导致内存泄漏,但是请记住,如果指针指向使用 new 分配的数据,并且它是指向该数据的唯一指针,则需要调用删除,然后再重新分配指针,否则会出现内存泄漏。

This is correct. The pointer is not const so you can change it to point to something else if you want. In this case it won't cause a meory leak but remember that if the pointer points to data allocated with new and it is the only pointer to that data then you need to call delete before reassigning the pointer otherwise you'll have a meory leak.


额外问题:并删除指针的常数?会是UB吗?

Extra question: and removing the constness of pointer? Would be UB?

如果您尝试修改 const 您从其中删除了 const 的对象,在本例中就是这样做的。只需删除 const 是可以的,有时是需要的,但是除非它不是 const ,否则您永远不能修改该对象。首先。例如,以下内容是合法的,因为 foo 不是 const

It is only UB if you try to modify a const object you removed const from, which you do in this case. Just removing const is okay, and sometimes needed, but you are never allowed to modify the object unless it was not const to begin with. For example the following is legal since foo is not const.

int foo = 42;

void bar(int const& baz) { const_cast<int&>(baz) = 21; }

int main()
{
    bar(foo);
}

const int foo = 42;

void bar(int const& baz) { const_cast<int&>(baz) = 21; }

int main()
{
    bar(foo);
}

由于 foo const

这篇关于当原始数据为const时,是否要修改指针所指向的UB?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆