[ create a new paste ] login | about

Link: http://codepad.org/MikKgG1W    [ raw code | output | fork ]

C++, pasted on Oct 24:
#include <iostream>
#include <vector>
#include <boost/ref.hpp>

template <class T> void func( T obj )
{
    obj.print();
}

template <class T> T & ref(T & r) { return r; } 


template <class T>
void func2( boost::reference_wrapper<T> obj )
{
    obj.get().print();
}


struct A
{
    A(){}
    A( A const & r ){ cout << "\tコピー発生" << endl;}
    void print(){ cout << "\tA::print" << endl; }
};


int main(int argc, char* argv[])
{
    A a;

    cout << "\nfunc( ref(a) )" << endl;
    func( ref(a) ); // A& とならずにコピーが発生

    cout << "\nfunc2( boost::ref(a) ) -- boost::reference_wrapper<A>" << endl;
    func2( boost::ref(a) ); // コピーが発生しない

    cout << "\nvector<A>::push_back" << endl;
    vector<A> v;
    v.push_back( a ); // コピー発生
    v.begin()->print();

    cout << "\nvector<boost::reference_wrapper<A> >::push_back" << endl;
    vector<boost::reference_wrapper<A> > v2;
    v2.push_back( boost::ref(a) );    // 参照なのでコピーが発生しない
    A &a2 = *v2.begin();
    a2.print();

    return 0;
}


Output:
1
2
3
4
5
6
7
8
9
10
11
12
13
14

func( ref(a) )
	コピー発生
	A::print

func2( boost::ref(a) ) -- boost::reference_wrapper<A>
	A::print

vector<A>::push_back
	コピー発生
	A::print

vector<boost::reference_wrapper<A> >::push_back
	A::print


Create a new paste based on this one


Comments: