请看下面的代码片段,在这种情况下 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;
}
Run Code Online (Sandbox Code Playgroud)
我在 Visual Studio 2019 [C++ 14,发布] 中得到以下反汇编:
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 …Run Code Online (Sandbox Code Playgroud) 为什么这个代码在C++ 14甚至C++ 17下是不正确的?
template <typename T>
function<T(T, T)> ReturnLambda () {
return [] (T x, T y) { return x*y; };
// return [] (auto x, auto y) { return x*y; }; // also incorrect
}
int main() {
auto f = ReturnLambda();
cout << f(3, 4) << endl;
}
Run Code Online (Sandbox Code Playgroud)