Performance std::bind-作为绑定函数中的参数的向量
我有一个问题,哪种方法是最好的,将向量前向到有界函数 下面是两种方法的代码。在生产代码中,vector将包含大量数据,我希望尽可能避免复制它Performance std::bind-作为绑定函数中的参数的向量,performance,c++11,vector,stl,bind,Performance,C++11,Vector,Stl,Bind,我有一个问题,哪种方法是最好的,将向量前向到有界函数 下面是两种方法的代码。在生产代码中,vector将包含大量数据,我希望尽可能避免复制它 #include <iostream> #include <vector> #include <functional> void foo(const std::vector<uint16_t>& v) { for(const auto& c : v) { st
#include <iostream>
#include <vector>
#include <functional>
void foo(const std::vector<uint16_t>& v)
{
for(const auto& c : v)
{
std::cout << c;
}
std::cout << std::endl;
}
int main()
{
std::vector<uint16_t> vv{1, 2, 3, 4, 5, 6, 7, 8, 9, 0};
auto f1 = std::bind(&foo, vv); // 1)
auto f2 = std::bind(&foo, std::move(vv)); // 2)
f1();
f2();
}
#包括
#包括
#包括
void foo(const std::vector&v)
{
用于(常数自动和c:v)
{
std::cout这实际上取决于你想对绑定函数做什么
如果要复制它们(超出vv
的使用期限),这是正确的(并且要复制vv
)
这也是正确的,(vv
至少最初不会被复制。)
但在此之后,您将无法访问vv
然而,这是我可以从您的示例中推断出的最可能的情况:
如果绑定函数将在vv
仍处于活动状态时在本地使用,则示例中更可能希望f3
保留对vv
的“引用”。这是通过ref
约定完成的:
auto f3 = std::bind(&foo, std::ref(vv));
您向我们展示的代码存在哪些问题?您是否只想了解您应该使用的两个std::bind
调用中的哪一个?是的,我想了解您的意见,对于绑定大量数据(如STL容器),哪种方法是最好的(从性能角度来看)。
auto f2 = std::bind(&foo, std::move(vv)); // 2)
auto f3 = std::bind(&foo, std::ref(vv));