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

时间:2015-03-19 17:05:33

标签: pointers c++11 reference functional-programming pass-by-reference

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

这是我到目前为止所尝试的内容:

#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字节。我知道函数是一个繁重的包装器,但是通过引用传递仍然应该是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毫秒

1 个答案:

答案 0 :(得分:1)

我认为你做得对,如果你是在32位机器上,那么通过引用传递应该是4个字节。 sizeof给出了被引用事物的大小,而不是引用的大小。我认为你不需要使用&#39; ref&#39;在呼叫现场。

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