【发布时间】:2018-03-07 14:39:54
【问题描述】:
显然std::function::operator=(F &&f) 是required to behave 与std::function(std::forward<F>(f)).swap(*this); 完全相同。
除非我遗漏了什么,否则这个定义会导致一些多余的移动:
#include <functional>
#include <iostream>
struct A
{
A() {std::cout << "A()\n";}
A(const A &) {std::cout << "A(const A &)\n";}
A(A &&) {std::cout << "A(A &&)\n";}
A &operator=(const A &) {std::cout << "A &operator=(const A &)\n"; return *this;}
A &operator=(A &&) {std::cout << "A &operator=(A &&)\n"; return *this;}
~A() {std::cout << "~A()\n";}
void operator()() const {}
};
int main()
{
std::function<void()> f;
f = A{};
}
打印:
A() // Created by `A{}` A(A &&) // Moved into temporary `std::function`, but what's the point? A(A &&) // Moved into `f` ~A() ~A() ~A()
(在 GCC 7.2 和 Clang 3.8 上测试)
问题:为什么我们不能通过直接复制/移动(取决于值类别)到 LHS 存储中来消除一个移动?
编辑:我不是在问为什么这个动作没有被优化掉,而是为什么它一开始就被做了。
【问题讨论】:
-
您是否质疑为什么需要额外的移动或者为什么它没有被优化移除?
-
@Slava 我更感兴趣的是为什么需要额外的移动。
-
另外,我想知道为什么说 move 不使用
A重用堆分配的缓冲区? -
我认为你应该修改你的问题以明确这一点。
标签: c++ std-function