相关疑难解决方法(0)

为什么const_cast删除指针的constness而不是指向const的指针?

我理解它const_cast适用于指针和引用.

我假设输入const_cast应该是指针或引用.我想知道为什么如果输入是一个指针/引用,它不会删除constness const int

以下代码按预期工作.

  1. const_cast 多级指针

    int main()
    {
        using std::cout;
        #define endl '\n'
        const int * ip = new int(123);
        const int * ptr = ip;
        *const_cast<int*>(ptr) = 321;
        cout << "*ip: " << *ip << endl;  // value of *ip is changed to 321
    }
    
    Run Code Online (Sandbox Code Playgroud)

    但是当我尝试指向const int或引用时const int,该值似乎没有改变.

  2. const_cast 参考const int

    int main()
    {
        using std::cout;
        #define endl '\n'
        const int i = 123;
        const int & ri …
    Run Code Online (Sandbox Code Playgroud)

c++ const-cast

13
推荐指数
2
解决办法
1849
查看次数

演员中的中间指针必须是"const限定" - 为什么?

在以下代码中......

#include <stdlib.h>
#include <stdint.h>

extern void get_buffer_from_HW_driver(volatile uint32_t **p);

void getBuffer(volatile uint32_t **pp)
{
    // Write an address into pp, that is obtained from a driver
    // The underlying HW will be DMA-ing into this address,
    // so the data pointed-to by the pointer returned by this
    // call are volatile.
    get_buffer_from_HW_driver(pp);
}

void work()
{
    uint32_t *p = NULL;
    getBuffer((volatile uint32_t **)&p);
}
Run Code Online (Sandbox Code Playgroud)

...编译器正确地检测到对p内部指向的数据的任何潜在访问work都是危险的访问.按原样,代码指示编译器安全地发出优化掉重复读访问的代码*p- 这确实是错误的.

但奇怪的是,通过编译此代码发出警告......

$ gcc -c -Wall -Wextra -Wcast-qual …
Run Code Online (Sandbox Code Playgroud)

c gcc const volatile

9
推荐指数
1
解决办法
494
查看次数

标签 统计

c ×1

c++ ×1

const ×1

const-cast ×1

gcc ×1

volatile ×1