plaisthos plaisthos - 3 months ago 14
C++ Question

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

Answer

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.

Comments