Std :: functions and passing lambda functions

I have a class that accepts std::functionas a parameter which I assign lambda functions. It works in the constructor, but after that it stops working. The debugger says it fis "empty" after starting the first line. Why?

#include <iostream>
#include <string>
#include <functional>

typedef std::function<void(std::string)> const& fn;

class TestClass
{
public:
    TestClass(fn _f) : f(_f) { F(); }
    void F() { f("hello"); };

private:
    fn f;
};


int main()
{
    TestClass t([](std::string str) {std::cout << str << std::endl; });

    t.F();

    return 0;
}

The call t.F()causes an error. Why?

I can solve this by changing it to the following:

int main()
{
    fn __f = [](std::string str) {std::cout << str << std::endl; };
    TestClass t(__f);

    t.F();

    return 0;
}

but then again, it doesn’t work when I change fnto auto!

int main()
{
    auto __f = [](std::string str) {std::cout << str << std::endl; };
    TestClass t(__f);

    t.F();

    return 0;
}

What is the explanation of why this is happening?

+4
source share
2 answers

, (1) fn ( ); (2) std::function ; (3) .

TestClass t([](std::string str) {std::cout << str << std::endl; });
t.F();

, std::function, . std::function _f f. , f , t.F(); .

fn __f = [](std::string str) {std::cout << str << std::endl; };
TestClass t(__f);
t.F();

, (to const). __f, .

auto __f = [](std::string str) {std::cout << str << std::endl; };
TestClass t(__f);
t.F();

lambda , std::function, . std::function _f f. , f , t.F(); .


(1) fn , typedef std::function<void(std::string)> fn;, std::function , .
(2) , ++.

+5
typedef std::function<void(std::string)> const& fn;

std::function, std::function.

TestClass(fn _f) : f(_f) { F(); }
fn f;

const& std::function const& std::function. F() , , , , .

TestClass t([](std::string str) {std::cout << str << std::endl; });

std::function, . ( ;).

std::function .

TestClass std::function const&, .

, std::function const& - undefined , .F() .

fn __f = [](std::string str) {std::cout << str << std::endl; };

. std::function, , , __f.

, , , , . , .

TestClass t(__f);

( ), .

auto __f = [](std::string str) {std::cout << str << std::endl; };

__f (. , ), .

std::function. A std::function .

TestClass t(__f);

std::function , TestClass, .

.F() , undefined.

, , - std::function. . A std::function .

, - const&, . -, .

- . ( , _, ).

, std::function , SO .

+3

Source: https://habr.com/ru/post/1650560/


All Articles