C++ 11 通过引用或指针传递功能对象的正确方法?

C++ 11 correct way to pass a functional object by reference or pointer?

我试图在我的程序周围传递一个随机数生成器(我想使用一个),但是我似乎找不到通过引用传递它的方法。

这是我迄今为止尝试过的方法:

#include <iostream>
#include <random>
#include <functional>

using namespace std;

void test(const function<int()> arng0, const function<int()> & arng1, const function<int()> & arng2,
          const function<int()> frng0, const function<int()> & frng1, const function<int()> & frng2)
{
    cerr << "Auto - std::_bind size: " << sizeof(arng0) << endl;
    cerr << "Auto - std::_bind & size: " << sizeof(arng1) << endl;
    cerr << "Auto - std::_bind ref size: " << sizeof(arng2) << endl;

    cerr << "Functional size: " << sizeof(frng0) << endl;
    cerr << "Functional & size: " << sizeof(frng1) << endl;
    cerr << "Functional ref size: " << sizeof(frng2) << endl;
}

void main()
{
    default_random_engine e;
    uniform_int_distribution<int> dist(0, 100);

    auto autoRng = bind(ref(dist), ref(e));
    function<int()> funcRng = bind(ref(dist), ref(e));

    test(autoRng, autoRng, ref(autoRng),
        funcRng, funcRng, ref(funcRng));

    system("Pause");
}

它们的输出均为 24 字节。我知道 functional 是一个沉重的包装器,但是通过引用传递仍然应该是 4 个字节?

答案:

void testValue(const function<int()> arng0)
{
    arng0();
}

void testRef(const function<int()> & arng0)
{
    arng0();
}

    {// Pass by value
        auto start = high_resolution_clock::now();
        for (unsigned int i = 0; i < 100000; i++)
        {
            testValue(funcRng);
        }
        auto end = high_resolution_clock::now();
        auto total = duration_cast<milliseconds>(end - start).count();
        cerr << "TestVal time: " << total << endl;
    }
    {// Pass by ref
        auto start = high_resolution_clock::now();
        for (unsigned int i = 0; i < 100000; i++)
        {
            testRef(funcRng);
        }
        auto end = high_resolution_clock::now();
        auto total = duration_cast<milliseconds>(end - start).count();
        cerr << "TestRef time: " << total << endl;
    }

结果: 测试值时间:179 毫秒 测试参考时间:74 毫秒

我想你没看错,如果你在 32 位机器上,按引用传递应该是 4 个字节。 sizeof 为您提供所引用事物的大小,而不是引用的大小。我认为您不需要在调用站点使用 'ref'。

在此处查看 sizeof 文档: http://en.cppreference.com/w/cpp/language/sizeof