在初始化列表中初始化引用 [英] initialize reference in initialization list
问题描述
我被告知引用变量必须在初始化列表中初始化,但为什么这是错误的?
class Foo
{
public:
Foo():x(0){
y = 1;
}
private:
int& X;
int y
};
因为0是临时对象?如果是这样,什么样的对象可以引用绑定?
0不是一个左值,它是一个右值。
如果你引用 const >,那么你可以修改它。 code>,它会按预期工作。考虑这个:
int& x = 0;
x = 1; // wtf :(
这显然是一个没有,但 const& ;
可以绑定到临时(rvalues):
const int& x = 0;
x = 1; // protected :) [不会编译]
临时的生命期在构造器完成时结束。如果您为自己的常数使用静态存储,您将是安全的:
class Foo
{
public:
static const int Zero = 0;
Foo():x(Zero)// Zero有存储
{
y = 1;
}
private:
const int& X;
int y
};
I was told the reference variable must be initialized in the initialization list, but why this is wrong?
class Foo
{
public:
Foo():x(0) {
y = 1;
}
private:
int& x;
int y;
};
Because 0 is a temporary object? If so, what kind of object can reference be bound? The object which can take an address?
Thanks!
0 is not an lvalue, it's an rvalue. You cannot modify it, but you're trying to bind to a reference where it could be modified.
If you make your reference const
, it will work as expected. Consider this:
int& x = 0;
x = 1; // wtf :(
This obviously is a no-go. But const&
's can be bound to temporaries (rvalues):
const int& x = 0;
x = 1; // protected :) [won't compile]
Note that the life-time of the temporary is ended at the completion of the constructor. If you make static-storage for your constant, you'll be safe:
class Foo
{
public:
static const int Zero = 0;
Foo() : x(Zero) // Zero has storage
{
y = 1;
}
private:
const int& x;
int y;
};
这篇关于在初始化列表中初始化引用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!