dimanche 28 juin 2015

C++ pass by value / by reference function overload

There are 2 function overloads:

MyClass do_something(MyClass param);
const MyClass& do_something(const MyClass& param);

Then I do:

MyClass c1 {"c1"};
do_something(c1);  // I want this to be used by value overload
do_something(c1);  // this to be used by reference overload

Is there any special way to explicitly specify that argument is passed by value or by reference?

For move semantic there is std::move() I wonder if there is anything like std::copy() std::ref for my case?

P.S. It's not to be used in real program, just checking out by myself the difference of passing arguments, returning values and their behaviour in different ways and have all functions with the same name:

// pass by value (copy)
MyClass do_something(MyClass param) {
    cout << "do_something(MyClass param)" << endl;
    param.i = 100;
    return param;
}

// !!! Your normal habit when passing an argument to a function should be to pass by const reference. (thinking in c++)
// pass by reference (reference)
const MyClass& do_something(const MyClass& param) { // doesn't allow to modify the object
    cout << "do_something(MyClass& param)" << endl;
    return param;
}

// pass by move semantic (move)
MyClass&& do_something(MyClass&& param) {
    cout << "do_something(MyClass&& param)" << endl;
    param.name += "__after_do_something(MyClass&& param)";
    param.i = 100;
    return move(param);
}

// pass by pointer (reference)
MyClass* do_something(MyClass* const param) { // allows to modify object, but not pointer (address)
    cout << "do_something(MyClass* const param)" << endl;
    param->i = 100;
    // (*param).i = 100;  // the same as above
    return param;
}

Aucun commentaire:

Enregistrer un commentaire