【问题标题】:How to get rid of -Wpointer-arith如何摆脱-Wpointer-arith
【发布时间】:2019-03-20 14:21:56
【问题描述】:

这段代码:

void Pack::packUInteger(void **buffer, unsigned int payload){
    memcpy(*buffer, &payload, sizeof(unsigned int));
    *buffer += sizeof(unsigned int);    
}

产生这个警告,我想摆脱它而不告诉编译器忽略它:

src/messaging/Pack.cpp: In static member function ‘static void Pack::packUInteger(void**, unsigned int)’:
src/messaging/Pack.cpp:33:10: warning: pointer of type ‘void *’ used in arithmetic [-Wpointer-arith]
  *buffer += sizeof(unsigned int);
  ~~~~~~~~^~~~~~~~~~

我知道它应该需要取消引用和强制转换,但我不知道如何正确地做到这一点。

感谢互联网! :)

【问题讨论】:

    标签: c++ pointers void-pointers pointer-to-pointer


    【解决方案1】:

    除非您显示指针指向的内容,否则无法验证这是否正确。

    但是考虑到您尝试将指针递增sizeof(unsigned int),如果*buffer 指向unsigned int 数组的元素,并且您尝试将指针递增到下一个兄弟,这将是有意义的。

    正确的做法是:

    auto ptr = static_cast<unsigned*>(*buffer);
    *buffer = ptr + 1;
    

    另一方面,如果指向原始存储,例如std::byte,正确的做法是:

    auto ptr = static_cast<std::byte*>(*buffer);
    *buffer = ptr + sizeof payload;
    

    我建议不要使用void**,而是如下:

    template <class T>
    std::byte* pack(std::byte* buffer, T payload) {
        static_assert(std::is_trivially_copyable_v<T>);
        std::memcpy(buffer, std::addressof(payload), sizeof payload);
        return buffer + sizeof payload;
    }
    

    【讨论】:

    • 我应该提到我无权访问 std::,因为代码应该在英特尔 SGX 飞地中运行 :) 除此之外,您的回答真的很有帮助!谢谢!
    • @larslars std:: 的东西在这里都不是绝对必要的。使用unsigned char 而不是std::byte。将string.h 包含在::memcpy 中。您可以自己轻松实现nonstd::addressof。 std::is_trivially_copyable 实现起来可能并不简单,但可以删除断言并单独记录需求。
    • 是的,谢谢它没有它也能工作。我们有自己的 memcpy,我正在考虑实现地址。我将在进行过程中添加完整性检查(内存边界、范围检查等),但我将不得不更多地考虑 is_trivially_copyable :)
    【解决方案2】:

    嗯,你正在增加一个void 指针。
    void的大小是多少??

    您应该在递增指针之前将指针转换为正确的类型。
    sizeof 以字节为单位给出大小,因此正确的类型应该是uint8_t 或unsigned char。

    *buffer = (uint8_t*)(*buffer) + sizeof(unsigned int);

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-01-28
      • 2013-10-31
      • 2020-10-19
      • 2019-12-01
      • 2013-01-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多