Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing by reference options in C++

I want to pass an object of Class A (call it a) by reference (in the broad sense, i.e. either by A& or by A*) to the constructor of another Class B. I do not want 'a' to be modified inside B ('a' is read only and it is big in size which is why I want to pass it by reference). I know of two options:

1) Pass 'a' as

const A & a_

2) Pass 'a' as

const A * a_

The disadvantage of option 1 is that I can mistakenly pass an r-value. The disadvantage of option 2 is that I can mistakenly pass a null pointer.

My questions are: 1) Am I right about the disadvantages above? 2) Is there another recommended way of passing 'a' by reference?

I saw the answers in the link below. But I am curious if there are other options than what is posted in that question. Are there benefits of passing by pointer over passing by reference in C++?

like image 338
Ned_the_Dolphin Avatar asked Oct 29 '15 18:10

Ned_the_Dolphin


2 Answers

Pass by const A &.

You can prevent accidental passing of rvalues by declaring an rvalue overload of that function = delete. For example:

struct A { };

void func(const A & a) { }
void func(A && a) = delete;

int main()
{
    A a;
    func(a);   // compiles
    func(A()); // doesn't compile
}
like image 127
emlai Avatar answered Oct 21 '22 16:10

emlai


Take a look at std::reference_wrapper's constructors: http://en.cppreference.com/w/cpp/utility/functional/reference_wrapper/reference_wrapper

It has an extra deleted constructor that takes rvalue reference, so if you try to pass an rvalue to it, that constructor wins overload resolution and you get an error.

You can do the same thing: declare both const A& and A&& constructors, and delete the latter. Then nobody will be able to pass in an rvalue.

like image 42
Brian Bi Avatar answered Oct 21 '22 16:10

Brian Bi