当原始数据为常量时,修改指针指向的位置是否是 UB?

Is it UB to Modify where pointer points, when original data is const?

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

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

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

附加问题:并更改 const 指针的非 const 数据?会是UB吗?示例:

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

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

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

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

如果您尝试修改从中删除 constconst 对象,这只是 UB,在本例中您就是这样做的。只删除 const 是可以的,有时也需要,但您永远不能修改对象,除非它不是 const 开始的。例如以下是合法的,因为 foo 不是 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);
}

不合法,因为 fooconst

第一个片段中的代码 100% 正确。您有一个指向 const p 的指针,您将其重新指向其他内容。一切都很好,完好无损。

第二段代码格式错误。如果原始对象是 const 限定的(字符串文字是),则在删除 constness 后不能修改对象。