为什么要按值传递string_view?为什么Visual Studio不能优化这一点?

Why pass string_view by value? And why can't Visual Studio optimize this?

本文关键字:为什么 Studio 不能 这一点 优化 Visual view 按值传递 string      更新时间:2023-10-16

根据我的直觉,我认为新string_view需要通过引用传递,因为这更有效(仅传递指针而不是完整的类(。 但是,一些来源表明最好按值传递它,避免"别名"问题。

  • C++视图类型:按常量传递还是按值传递?
  • https://abseil.io/tips/1

在尝试几种替代方案时,我确认了我的直觉,即如果函数只执行转发string_view(所有源代码都使用/Ox编译(而通过引用传递会更快

例如,此代码

extern auto otherMethodByReference(const std::string_view &input) -> void;
auto thisMethodByReference(int value, const std::string_view &input) -> void
{
otherMethodByReference(input);
}

导致此程序集

00000   48 8b ca     mov     rcx, rdx
00003   e9 00 00 00 00   jmp     ?otherMethodByReference@@YAXAEBV?$basic_string_view@DU?$char_traits@D@std@@@std@@@Z ; otherMethodByReference

虽然这段代码

extern auto otherMethodByValue(std::string_view input) -> void;
auto thisMethodByValue(int value, std::string_view input) -> void
{
otherMethodByValue(input);
}

导致此程序集

00000   48 83 ec 38  sub     rsp, 56            ; 00000038H
00004   0f 10 02     movups  xmm0, XMMWORD PTR [rdx]
00007   48 8d 4c 24 20   lea     rcx, QWORD PTR $T1[rsp]
0000c   0f 29 44 24 20   movaps  XMMWORD PTR $T1[rsp], xmm0
00011   e8 00 00 00 00   call    ?otherMethodByValue@@YAXV?$basic_string_view@DU?$char_traits@D@std@@@std@@@Z ; otherMethodByValue
00016   48 83 c4 38  add     rsp, 56            ; 00000038H
0001a   c3       ret     0

很明显,您可以看到在堆栈上创建了string_view的副本,然后传递给其他方法。

但是,我想知道,为什么编译器不对此进行优化,而只是将string_view参数直接传递给其他方法。 毕竟,在 Windows x64 ABI 中,大于寄存器大小的类的按值传递始终是通过复制堆栈上的寄存器并在正确的寄存器中传递指向它的指针来完成的。 我希望在此示例代码中,编译器只需将指针转发到下一个函数,就像在按引用传递的情况下一样。 毕竟,编译器可以看到参数的值之后没有使用,所以它不需要复制,而可以直接转发地址。

我尝试将 std::move 添加到通话中,如下所示:

auto thisMethodByValueAndMove(int value, std::string_view input) -> void
{
otherMethodByValue(std::move(input));
}

但这似乎无济于事。

Visual Studio 2017编译器无法优化这一点有什么原因吗? 其他编译器是否优化了此模式?

X64 调用约定不允许将参数分散到不同的寄存器中。 编译器可以通过 rcx 和 rdx 传递string_view,但 ABI 反对这一点。 https://learn.microsoft.com/en-us/cpp/build/x64-calling-convention?view=vs-2019

相关文章: