You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何让GCC对结合std::move的std::bit_cast进行优化?

GCC下std::bit_cast的拷贝优化问题

考虑以下代码:

#include <cstdint>
#include <bit>
#include <utility>

struct A { uint32_t a[100]; };
struct B { uint16_t b[200]; };

void test(const A&);

void foo() {
    B tmp;
    test(std::bit_cast<A>(std::move(tmp)));
}

void bar() {
    B tmp;
    test(reinterpret_cast<A&>(tmp));
}

在Clang 15搭配-O3编译选项时,foo和bar函数的实现是等价的,但在GCC 12.2搭配-O3时,foo函数会执行数据拷贝(rep movsq指令)。

对应的汇编代码如下:

foo():
        sub     rsp, 808
        mov     ecx, 50
        lea     rdi, [rsp+400]
        mov     rsi, rsp
        rep movsq
        lea     rdi, [rsp+400]
        call    test(A const&)
        add     rsp, 808
        ret
bar():
        sub     rsp, 408
        mov     rdi, rsp
        call    test(A const&)
        add     rsp, 408
        ret

请问使用哪个编译器选项能让GCC实现和Clang类似的优化?感谢解答。补充说明:-Ofast选项对此问题无帮助。


[编辑]

根据用户user17732522提供的解答,我修改了代码如下:

#include <cstdint>
#include <bit>

struct A { uint32_t a[100]; };
struct B { uint16_t b[200]; };

void test(const A&);

void foo(B arg) {
    test(std::bit_cast<A>(arg));
}

void bar(B arg) {
    test(reinterpret_cast<A&>(arg));
}

现在GCC和Clang都会对foo函数执行数据拷贝。由此看来,std::bit_cast原本就不打算覆盖这类场景。


内容的提问来源于stack exchange,提问作者Home of the Brave

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.17 23:01:12