当移动-构造std::function从一个对象的λ,其中该拉姆达具有由值捕获,看来该物体的移动,构造函数,是值捕获被调用两次。考虑
#include <功能>
#include <iostream>
结构体
{
整数值 = 1;
Foo() = 默认值;
Foo(const Foo &) {}
富(富&&)
{
std::cout << "移动构造函数" << std::endl;
}
};
int main()
{
福福;
自动 lambda = [=]() { 返回 foo.value; };
std::cout << "---------" << std::endl;
std::function<int()> func(std::move(lambda));
std::cout << "---------" << std::endl;
返回0;
}
输出是
---------
move ctor
move ctor
---------
Run Code Online (Sandbox Code Playgroud)
我在 Mac OS X Catalina 上工作,我的编译器是
g++-9 (Homebrew GCC 9.3.0) 9.3.0
Run Code Online (Sandbox Code Playgroud)
我用g++ -std=c++17. …
我的代码:
#include <iostream>
#include <functional>
using namespace std;
struct A {
A() = default;
A(const A&) {
cout << "copied A" << endl;
}
};
void foo(A a) {}
int main(int argc, const char * argv[]) {
std::function<void(A)> f = &foo;
A a;
f(a);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
我在控制台上看到"复制A"两次.为什么对象被复制两次而不是一次?我怎样才能正确预防?
我试图理解currying和调用一个函数的概念,该函数连接三个字符串,但只传递两个字符串并使用第二个参数两次.
但是,当我这样做时,第二个参数根本没有被发送到函数,它打印出一个空字符串.这是一个非常明显的错误吗?
string concatthreestrings(string a,string b,string c){
cout<<"Value of A: "<<a<<endl;
cout<<"Value of B: "<<b<<endl;
cout<<"Value of C: "<<c<<endl;
return a+b+c;
}
int main()
{
typedef std::function< string( string,string) > fun_t ;
using namespace std::placeholders;
fun_t fn = std::bind( concatthreestrings, _1, _2, _2);
cout<<endl<<fn( "First","Second")<<endl;
}
Run Code Online (Sandbox Code Playgroud)
这是给出以下输出.不使用_2两次意味着第二个参数将被传递给第二个和第三个.如果在其位置使用字符串,其工作正常.
