就地构造 std::函数目标
Constructing std::function target in-place
我理解为std::function
的典型用法
#include <iostream>
#include <functional>
using namespace std;
class C {
public:
C() { cout << "CREATING" << endl; }
C(const C&) { cout << "COPY C "<< endl; };
C(C&&) { cout << "MOVE C " << endl; };
~C() { cout << "DELETING"<< endl; }
C& operator =(const C&) {
cout << "COPY A " << endl; return *this;
};
C& operator =(C&&) {
cout << "MOVE A" << endl; return *this;
};
void operator ()() const { cout << "CALLING" << endl; }
};
int main(int argc, char *argv[]) {
function<void()> f = C();
f();
return 0;
}
输出后产量
CREATING
MOVE C
DELETING
CALLING
DELETING
显然,临时对象是在堆栈上创建的,然后移动到函数对象中。如果未提供移动构造函数,则改为复制它。
是否有一种标准方法可以在不需要临时对象的情况下设置目标?
§20.9.11.2.1 中的标准规定,从任何函子F f
构造function
的方式(假设f
是非空的,强调我的):
*this
以使用std::move(f)
初始化的f
的副本为目标
所以没有办法就地构造一个function
。这让你在招致该移动之间做出选择:
function<void()> f1 = C{};
或者传入一些移动/复制成本更低的包装器C
,无论是外部管理
C manage_me;
function<void()> f2 = std::ref(manage_me);
。或分配给operator()
function<void()> f3 = std::bind(&C::operator(), std::make_shared<C>());
如果operator()
碰巧过载,最后一个可能会引起一些头痛,因为您必须将其转换为正确的类型,这是以前版本都不必处理的问题。
function<void()> f4 = std::bind(
static_cast<void(C::*)()>(&C::operator()),
std::make_shared<C>()
);
您可以使用
std::bind
但实际上不需要为此实现operator()
:
int main(int argc, char *argv[]) {
C c;
function<void()> f = std::bind( &C::operator(), &c );
f();
return 0;
}
输出:
CREATING
CALLING
DELETING
当然,在这种情况下,您需要正确维护对象 C 的生存期。要使std::function
拥有C
实例并使其更加就地构造,可以使用std::shared_ptr
:
int main(int argc, char *argv[]) {
function<void()> f = std::bind( &C::operator(), std::make_shared<C>() );
f();
return 0;
}
相关文章:
- 线性优化目标函数中的绝对值
- 字符串函数在目标C++上运行时C++返回空
- 目标是找到两个 c 字符串之间的公共前缀(必须使用特定的函数标头)
- 为什么即使链接器找到目标文件,我的程序也看不到函数定义?
- 从.o目标文件中提取函数的原始机器代码?
- Google Mock:在目标类的构造函数中实例化的模拟私有变量成员
- Cgal二次规划目标函数
- linux 是否"rename"函数调用块,直到复制(当源和目标在不同磁盘中时)完成
- C++ lambda 函数 - 如何返回与目标相比最接近的矢量元素
- 一个函数怎么能完成它的目标,只是在返回主函数后崩溃?
- 将参数转换为目标类型时,复制用于直接初始化的构造函数省略
- 如何从std ::函数中提取和执行目标
- 我有一个构造函数,但我需要将输出返回到 main.cpp.我无法使用获取字符串功能!!任何想法如何实现这一目标?
- Turbo C++:为 malloc 函数生成目标代码
- 如何创建一个qmake函数来创建一个自定义的make目标
- 在目标函数中使用迭代器的 STL 算法
- 外部"C"已编译目标代码中的函数
- 没有用于初始化 - C++ 和目标 C 的匹配构造函数
- 就地构造 std::函数目标
- C++0x:std::函数::目标和模板参数错误