gpt4 book ai didi

c++ - 从 const_cast 中取消引用指针是否总是会调用未定义的行为?

转载 作者:太空狗 更新时间:2023-10-29 19:44:17 26 4
gpt4 key购买 nike

请参阅以下内容:

struct A
{
std::string* get() const
{
//return const_cast<std::string*>(&m_pObj);
return &const_cast<A*>(this)->m_pObj;
}

std::string m_pObj;
};

正在取消引用 this UB 的 const_cast?是否有任何时候取消引用 const_casting 指针常量的结果不会调用 UB?

(我知道上面的例子是不好的做法,不好的设计,可以用可变的来解决——这不是重点)

最佳答案

Is dereferencing const_cast of this UB? Is there any time dereferencing the result from const_casting the constness of a pointer away doesn't invoke UB?

不总是,仅当对象常量(A实例是const A x;) 取消引用用于修改数据。如果它仅用于读取,则它不会是未定义的行为,如果对象不是 const,(可能根本不是,可能是对非 const 对象的 const 引用)它不会要么是 UB。

关于c++ - 从 const_cast 中取消引用指针是否总是会调用未定义的行为?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11053982/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com