Passing by reference options in C++
I want to pass an object of Class A (call it a) by reference (in the broad sense, ie 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++?
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
}
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.
代码:
#include <iostream>
using namespace std;
struct A
{ };
int func_one(A& var) {
A * insertVal=new A;
if (&var==nullptr)
return 0;
else
return 1;
}
int main() {
A refVar;
int x;
x=func_one(refVar);
return 1;
}
链接地址: http://www.djcxy.com/p/20730.html
下一篇: 在C ++中通过引用选项传递