开发者

c++ operator= method for const references

I am writing class with a const reference like this:

class B;

class foo {
  const B& b;

  foo(const B& newb): b(newb) { }

  void operator=(const foo & foo2) {
      // This does not work
      foo.b = foo2.b;
  }   
};

I am trying to define a working operator= Obviously = does not work since I am not allowd to change a cons开发者_JAVA技巧t reference. This there a way to let a reference point to another object?

If b is not const c++ will provide me with a working operator=. If I define one member as const cl will spit out:

warning C4512: 'foo' : assignment operator could not be generated


The term you're looking for is "rebind." As in "is it possible to rebind a reference?" The answer is "no, references are defined as not being rebindable." But you can use a pointer and change what it points to:

class B;

class foo {
    B* b;

    foo(const B& newb)
    {
        b = &newb;
    }

    void operator=(const foo& foo2)
    {
        b = &foo2.b;
    }   
};

However, this risks dangling pointers if the object being assigned to outlives the object used for the assignment (same problem for the constructor, by the way). There's a good chance that you don't need references or pointers at all:

class B;

class foo {
    B b;

    foo(const B& newb): b(newb) { }

    void operator=(const foo& foo2)
    {
        b = foo2.b;
    }   
};

If you do need pointers/references (maybe B is a base class) then you'll want to look into smart pointers to handle object lifetime issues.


I don't think your code makes any sense. There is no object called foo, so foo = foo2 is meaningless.


No, once a reference is initialized, the object it references cannot be changed. If you need to do that, a pointer is more appropriate.


You cannot change which object a reference refers to. Use a pointer in your class instead.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜