初始化初始化列表中的引用

时间:2010-02-09 20:16:26

标签: c++

我被告知必须在初始化列表中初始化引用变量,但为什么这是错误的?

   class Foo
    {
    public: 
        Foo():x(0) {      
         y = 1;
        }
    private:
        int& x;
        int y;
    };

因为0是临时对象?如果是这样,可以引用什么样的对象?可以获取地址的对象?

谢谢!

3 个答案:

答案 0 :(得分:15)

0不是左值,它是右值。你不能修改它,但是你试图绑定到可以修改它的引用。

如果您引用const,它将按预期工作。考虑一下:

int& x = 0;
x = 1; // wtf :(

这显然是不行的。但const&可以绑定临时(rvalues):

const int& x = 0;
x = 1; // protected :) [won't compile]

请注意,临时的生命周期在构造函数完成时结束。如果您为常量进行静态存储,那么您将是安全的:

class Foo
{
public:
    static const int Zero = 0;

    Foo() : x(Zero) // Zero has storage
    {
        y = 1;
    }
private:
    const int& x;
    int y;
};

答案 1 :(得分:0)

长期参考必须绑定到lvalue。基本上,正如你雄辩地说的那样,一个具有明确地址的对象。如果它们绑定到临时值,则临时值将被销毁,而引用仍然引用它并且结果未定义。

短暂的const引用(局部函数变量和函数参数)可以绑定到临时值。如果是,则在参考超出范围之前,保证临时不会被销毁。

演示代码:

#include <iostream>

class Big {
 public:
   Big() : living_(true), i_(5) { // This initialization of i is strictly legal but
      void *me = this;            // the result is undefined.
      ::std::cerr << "Big constructor called for " << me << "\n";
   }
   ~Big() {
      void *me = this;
      living_ = false;
      ::std::cerr << "Big destructor called for " << me << "\n";
   }

   bool isLiving() const { return living_; }
   const int &getIref() const;
   const int *getIptr() const;

 private:
   ::std::string s_;
   bool living_;
   const int &i_;
   char stuff[50];
};

const int &Big::getIref() const
{
   return i_;
}

const int *Big::getIptr() const
{
   return &i_;
}

inline ::std::ostream &operator <<(::std::ostream &os, const Big &b)
{
   const void *thisb = &b;
   return os << "A " << (b.isLiving() ? "living" : "dead (you're lucky this didn't segfault or worse)")
             << " Big at " << thisb
             << " && b.getIref() == " << b.getIref()
             << " && *b.getIptr() == " << *b.getIptr();
}

class A {
 public:
   A() : big_(Big()) {}

   const Big &getBig() const { return big_; }

 private:
   const Big &big_;
};

int main(int argc, char *argv[])
{
   A a;
   const Big &b = Big();
   const int &i = 0;
   ::std::cerr << "a.getBig() == " << a.getBig() << "\n";
   ::std::cerr << "b == " << b << "\n";
   ::std::cerr << "i == " << i << "\n";
   return 0;
}

输出:

Big constructor called for 0x7fffebaae420
Big destructor called for 0x7fffebaae420
Big constructor called for 0x7fffebaae4a0
a.getBig() == A living Big at 0x7fffebaae420 && b.getIref() == -341121936 && *b.getIptr() == -341121936
b == A living Big at 0x7fffebaae4a0 && b.getIref() == 0 && *b.getIptr() == 0
i == 0
Big destructor called for 0x7fffebaae4a0

答案 2 :(得分:0)

好吧,你永远不能改变它,0永远不能等于0以外的任何东西。

 class Foo
    {
    public: 
        Foo(int& a):x(a) {      
         y = 1;
        }
    private:
        int& x;
        int y;
    };

或者,如果您的引用是常量,则可以执行此操作,因为0只能等于零

相关问题