Search code examples
c++pointersreferencervalue-referencervalue

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++?


Solution

  • 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
    }