AskOverflow.Dev

AskOverflow.Dev Logo AskOverflow.Dev Logo

AskOverflow.Dev Navigation

  • 主页
  • 系统&网络
  • Ubuntu
  • Unix
  • DBA
  • Computer
  • Coding
  • LangChain

Mobile menu

Close
  • 主页
  • 系统&网络
    • 最新
    • 热门
    • 标签
  • Ubuntu
    • 最新
    • 热门
    • 标签
  • Unix
    • 最新
    • 标签
  • DBA
    • 最新
    • 标签
  • Computer
    • 最新
    • 标签
  • Coding
    • 最新
    • 标签
主页 / coding / 问题 / 78601070
Accepted
Harry
Harry
Asked: 2024-06-10 15:49:47 +0800 CST2024-06-10 15:49:47 +0800 CST 2024-06-10 15:49:47 +0800 CST

如何在数组指针类型参数上使用 std::bit_cast

  • 772

是否可以将数组第一个元素的地址作为参数传递给std::bit_cast.

#include <bit>
#include <iostream>

struct A {
    int a;
    int b;
    int c;
    int d;
    int e;

    void print() {
        std::cout << a << ", " << b << ", " << c << ", " << d << ", " << e << std::endl;
    }
};

int main() {
    char arr[20]{};
    // arr is filled with some data
    A a = std::bit_cast<A>(arr);
    a.print();

    const char* arrp = arr;
    // doesn't compile
    A b = std::bit_cast<A>(arrp);
    b.print();
}

错误

<source>: In function 'int main()':
<source>:23:27: error: no matching function for call to 'bit_cast<A>(const char*&)'
   23 |     A b = std::bit_cast<A>(arrp);
      |           ~~~~~~~~~~~~~~~~^~~~~~
In file included from <source>:1:
/opt/compiler-explorer/gcc-13.2.0/include/c++/13.2.0/bit:81:5: note: candidate: 'template<class _To, class _From> constexpr _To std::bit_cast(const _From&) requires  sizeof (_To) == sizeof (_From) && __is_trivially_copyable(_To) && __is_trivially_copyable(_From)'
   81 |     bit_cast(const _From& __from) noexcept
      |     ^~~~~~~~
/opt/compiler-explorer/gcc-13.2.0/include/c++/13.2.0/bit:81:5: note:   template argument deduction/substitution failed:
/opt/compiler-explorer/gcc-13.2.0/include/c++/13.2.0/bit:81:5: note: constraints not satisfied
/opt/compiler-explorer/gcc-13.2.0/include/c++/13.2.0/bit: In substitution of 'template<class _To, class _From> constexpr _To std::bit_cast(const _From&) requires  sizeof (_To) == sizeof (_From) && __is_trivially_copyable(_To) && __is_trivially_copyable(_From) [with _To = A; _From = const char*]':
<source>:23:27:   required from here
/opt/compiler-explorer/gcc-13.2.0/include/c++/13.2.0/bit:81:5:   required by the constraints of 'template<class _To, class _From> constexpr _To std::bit_cast(const _From&) requires  sizeof (_To) == sizeof (_From) && __is_trivially_copyable(_To) && __is_trivially_copyable(_From)'
/opt/compiler-explorer/gcc-13.2.0/include/c++/13.2.0/bit:83:27: note: the expression 'sizeof (_To) == sizeof (_From) [with _To = A; _From = const char*]' evaluated to 'false'
   83 |     requires (sizeof(_To) == sizeof(_From))
      |              ~~~~~~~~~~~~~^~~~~~~~~~~~~~~~~
Compiler returned: 1
c++
  • 2 2 个回答
  • 71 Views

2 个回答

  • Voted
  1. Best Answer
    Jan Schultke
    2024-06-10T16:17:13+08:002024-06-10T16:17:13+08:00

    数组不是指针。std::bit_cast<A>(arr);是正确的。 arr通过引用传递,并且由于std::bit_cast具有const From&参数,因此From推断为char[20],并且您实际上传递了const char(&)[20],即“对 20 个数组的引用const char”。这与传递指针不同。

    另一方面,std::bit_cast<A>(arrp);尝试将一个指针(大小8大概为 )进行位转换为一个A(大小20大概为 ),并且不能在不同大小的类型之间进行位转换。

    这里更好的方法是通过 进行类型双关std::memcpy,这种方法之所以有效,是因为A它可以轻松复制并且具有隐式生命周期:

    const char* arrp = arr;
    
    A b;
    std::memcpy(&b, arrp, sizeof(b));
    b.print();
    

    另请参阅在 C++ 中进行类型双关的现代、正确方法是什么?

    • 5
  2. Chukwujiobi Canon
    2024-06-10T16:31:51+08:002024-06-10T16:31:51+08:00

    在某些情况下, Anarray可以退化为指针,但在这种情况下,它不会。相反,它仍然是一个array,并且std::bit_cast可以获取其地址并将其视为连续的内存块。[1]

    在第二种情况下,arrp是一个指针。当您传递arrp给时std::bit_cast,您传递的是一个指针,而不是一块内存。这是一个重要的区别。如果您根据 cppreference 查看建议的[cppreference]的可能实现std::bit_cast ,它表明函数参数的地址最终将被获取并作为参数传递给std::memcpy:

    template<class To, class From>
    std::enable_if_t<
        sizeof(To) == sizeof(From) &&
        std::is_trivially_copyable_v<From> &&
        std::is_trivially_copyable_v<To>,
        To>
    // constexpr support needs compiler magic
    bit_cast(const From& src) noexcept
    {
        static_assert(std::is_trivially_constructible_v<To>,
            "This implementation additionally requires "
            "destination type to be trivially constructible");
     
        To dst;
        std::memcpy(&dst, &src, sizeof(To));
        return dst;
    }

    现在看到问题了?指针参数是意外的,因为它仍然会获取的地址src。您可以直接使用实现的核心,而无需进行所有检查。

    必须注意:您确实意识到您现在处于非常低的水平,并且很多东西都不可靠。例如,int可能不完全是32位。断言sizeof struct A == sizeof char arr[20]不能保证所有实现都适用。


    [1]它不会衰变,因为它经过const&

    • 3

相关问题

  • 为什么编译器在这里错过矢量化?

  • 使用带有库的 CMake 编译错误[关闭]

  • 每次我尝试运行预制时都会抛出错误

  • 如何在 C++ 中创建类似于 std::byte 的八位字节类型?

  • C++17 中 std::byte 只能按位运算?

Sidebar

Stats

  • 问题 205573
  • 回答 270741
  • 最佳答案 135370
  • 用户 68524
  • 热门
  • 回答
  • Marko Smith

    Vue 3:创建时出错“预期标识符但发现‘导入’”[重复]

    • 1 个回答
  • Marko Smith

    为什么这个简单而小的 Java 代码在所有 Graal JVM 上的运行速度都快 30 倍,但在任何 Oracle JVM 上却不行?

    • 1 个回答
  • Marko Smith

    具有指定基础类型但没有枚举器的“枚举类”的用途是什么?

    • 1 个回答
  • Marko Smith

    如何修复未手动导入的模块的 MODULE_NOT_FOUND 错误?

    • 6 个回答
  • Marko Smith

    `(表达式,左值) = 右值` 在 C 或 C++ 中是有效的赋值吗?为什么有些编译器会接受/拒绝它?

    • 3 个回答
  • Marko Smith

    何时应使用 std::inplace_vector 而不是 std::vector?

    • 3 个回答
  • Marko Smith

    在 C++ 中,一个不执行任何操作的空程序需要 204KB 的堆,但在 C 中则不需要

    • 1 个回答
  • Marko Smith

    PowerBI 目前与 BigQuery 不兼容:Simba 驱动程序与 Windows 更新有关

    • 2 个回答
  • Marko Smith

    AdMob:MobileAds.initialize() - 对于某些设备,“java.lang.Integer 无法转换为 java.lang.String”

    • 1 个回答
  • Marko Smith

    我正在尝试仅使用海龟随机和数学模块来制作吃豆人游戏

    • 1 个回答
  • Martin Hope
    Aleksandr Dubinsky 为什么 InetAddress 上的 switch 模式匹配会失败,并出现“未涵盖所有可能的输入值”? 2024-12-23 06:56:21 +0800 CST
  • Martin Hope
    Phillip Borge 为什么这个简单而小的 Java 代码在所有 Graal JVM 上的运行速度都快 30 倍,但在任何 Oracle JVM 上却不行? 2024-12-12 20:46:46 +0800 CST
  • Martin Hope
    Oodini 具有指定基础类型但没有枚举器的“枚举类”的用途是什么? 2024-12-12 06:27:11 +0800 CST
  • Martin Hope
    sleeptightAnsiC `(表达式,左值) = 右值` 在 C 或 C++ 中是有效的赋值吗?为什么有些编译器会接受/拒绝它? 2024-11-09 07:18:53 +0800 CST
  • Martin Hope
    The Mad Gamer 何时应使用 std::inplace_vector 而不是 std::vector? 2024-10-29 23:01:00 +0800 CST
  • Martin Hope
    Chad Feller 在 5.2 版中,bash 条件语句中的 [[ .. ]] 中的分号现在是可选的吗? 2024-10-21 05:50:33 +0800 CST
  • Martin Hope
    Wrench 为什么双破折号 (--) 会导致此 MariaDB 子句评估为 true? 2024-05-05 13:37:20 +0800 CST
  • Martin Hope
    Waket Zheng 为什么 `dict(id=1, **{'id': 2})` 有时会引发 `KeyError: 'id'` 而不是 TypeError? 2024-05-04 14:19:19 +0800 CST
  • Martin Hope
    user924 AdMob:MobileAds.initialize() - 对于某些设备,“java.lang.Integer 无法转换为 java.lang.String” 2024-03-20 03:12:31 +0800 CST
  • Martin Hope
    MarkB 为什么 GCC 生成有条件执行 SIMD 实现的代码? 2024-02-17 06:17:14 +0800 CST

热门标签

python javascript c++ c# java typescript sql reactjs html

Explore

  • 主页
  • 问题
    • 最新
    • 热门
  • 标签
  • 帮助

Footer

AskOverflow.Dev

关于我们

  • 关于我们
  • 联系我们

Legal Stuff

  • Privacy Policy

Language

  • Pt
  • Server
  • Unix

© 2023 AskOverflow.DEV All Rights Reserve