在C++中通过值传递或通过常量引用传递是否更好?
我想知道哪个是更好的做法.我意识到通过常量引用传递应该在程序中提供更好的性能,因为你没有复制变量.
如果我们想用不同的类型初始化引用,我们需要将其设置为 const (const type*),以便可以隐式生成临时对象并将引用绑定到 with。或者,我们可以使用右值引用并实现相同的[1]:
右值引用可用于延长临时对象的生命周期(注意,对 const 的左值引用也可以延长临时对象的生命周期,但不能通过它们进行修改):
[...]
样品
情况1
double x = 10;
int &ref = x; //compiler error (expected)
Run Code Online (Sandbox Code Playgroud)
案例2
double x = 10;
const int &ref = x; //ok
Run Code Online (Sandbox Code Playgroud)
案例3
double x = 10;
int &&ref = x; //ok
Run Code Online (Sandbox Code Playgroud)
如果我们尝试对 const 指针(const type* &)做同样的事情,并用非 const 指针(type*)初始化它,与我预期的不同,只有情况 2 有效。为什么情况3会导致编译器错误?为什么没有生成临时文件?
情况1
int x = 10;
int *pX = &x;
const int* &ref = pX; //compiler error (expected)
Run Code Online (Sandbox Code Playgroud)
案例2
int x = 10;
int *pX = &x;
const int* …Run Code Online (Sandbox Code Playgroud) 给定
int i = 42;
int* p = &i;
Run Code Online (Sandbox Code Playgroud)
我们做不到
const int * & d = p;
Run Code Online (Sandbox Code Playgroud)
在我目前的理解中,这是因为const int * & d可以读作“d是一个指向 an 的指针的引用int,它是一个const”,并且p是“指向 an 的指针int”,这意味着 RHS 需要变成一个临时的“指向 an 的指针”。 anint是一个const" 并且不能直接与引用绑定(如在 LHS 上)。我们需要有,比如说,const int* const& d = p;。可能的参考文献:1、2。
也就是说,请考虑以下玩具代码:
template<typename T>
class X
{
public:
void fun(const T& d) { }
};
Run Code Online (Sandbox Code Playgroud)
起初我想如果我这样做
X<int*> x;
x.fun(p); …Run Code Online (Sandbox Code Playgroud)