gpt4 book ai didi

c++ - 低效率的 std::move()?

转载 作者:行者123 更新时间:2023-12-03 07:09:13 25 4
gpt4 key购买 nike

请看下面的代码片段,在这种情况下,std::move() 似乎效率很低。

class A {};

struct B {
double pi{ 3.14 };
int i{ 100 };
A* pa{ nullptr };
};

int main() {
B b;
std::vector<B> vec;
vec.emplace_back(b); // 1) without move
vec.emplace_back(std::move(b)); // 2) with move
return 0;
}

我在 visual studio 2019 [C++ 14, Release] 中得到了以下反汇编:

    vec.emplace_back(b);                // 1) without move
00E511D1 push eax
00E511D2 push 0
00E511D4 lea ecx,[vec]
00E511D7 call std::vector<B,std::allocator<B> >::_Emplace_reallocate<B> (0E512C0h)
vec.emplace_back(std::move(b)); // 2) with move
00E511DC mov eax,dword ptr [ebp-18h]
00E511DF cmp eax,dword ptr [ebp-14h]
00E511E2 je main+91h (0E511F1h)
00E511E4 movups xmm0,xmmword ptr [b]
00E511E8 movups xmmword ptr [eax],xmm0
00E511EB add dword ptr [ebp-18h],10h
00E511EF jmp main+9Eh (0E511FEh)
00E511F1 lea ecx,[b]
00E511F4 push ecx
00E511F5 push eax
00E511F6 lea ecx,[vec]
00E511F9 call std::vector<B,std::allocator<B> >::_Emplace_reallocate<B> (0E512C0h)

很容易看出 move 版本需要做更多不必要的工作。根据描述here ,编译器将为结构 B 生成一个简单的 move 构造函数,这个简单的 move 构造函数将采用复制语义

那么我的问题是:

  1. std::move() 对于这种情况是完全多余的。
  2. 此外,如果 std::move() 的参数有一个普通的 move 构造函数,则 std::move() 是多余的。
  3. 如果普通 move 构造函数执行与普通复制构造函数相同的操作,为什么编译器生成不同的反汇编?实际上,这是最让我困惑的。

最佳答案

  1. std::move() is completely redundant for this case.

技术上不是问题,但是是的,这是正确的。

  1. Moreover, if the parameter of std::move() has a trivial move constructor, then std::move() is redundant.

同上。

  1. if the trivial move constructor performs the same action as the trivial copy constructor, why the compiler generates different disassembly?

可能是因为您在其中调用了函数 std::move 而在另一个中未调用。

它不必生成不同的程序集,因为可观察到的行为是相同的。我的编译器生成相同的程序集。

关于c++ - 低效率的 std::move()?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64965605/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com