Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c++ operator= method for const references

Tags:

c++

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 const 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

like image 741
plaisthos Avatar asked Aug 04 '10 18:08

plaisthos


2 Answers

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.

like image 67
Max Lybbert Avatar answered Sep 24 '22 07:09

Max Lybbert


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

like image 41
Oliver Charlesworth Avatar answered Sep 22 '22 07:09

Oliver Charlesworth