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

Pointers C++;11通过引用或指针传递函数对象的正确方法?,pointers,c++11,reference,functional-programming,pass-by-reference,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, c

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

以下是我迄今为止所做的尝试:

#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");
}
#包括
#包括
#包括
使用名称空间std;
无效测试(常数函数arng0、常数函数和arng1、常数函数和arng2、,
常量函数frng0、常量函数和frng1、常量函数和frng2)
{

cerr我认为你说得对,如果你在32位机器上,通过引用传递应该是4字节。
sizeof
给出的是被引用对象的大小,而不是引用的大小。我认为你不需要在调用站点使用“ref”

请参见此处的
sizeof
文档:

事实上,如果我使用sizeof(ref(fp))或sizeof(&fp)检查大小,我会得到4个字节,但我不确定。你知道我可以用什么方法测试它是否通过引用传递吗?\u alignof()给我8个字节。你使用的是哪种编译器和版本、哪种操作系统、哪种优化标志?
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;
    }