Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reassignment of a reference

Suppose I have a class

class Foo
{
  public:
    ~Foo() { delete &_bar; }
    void SetBar(const Bar& bar)
    {
      _bar = bar;
    }
    const Bar& GetBar() { return _bar; }
  private:
    Bar& _bar;
}

And my usage of this class is as follows (assume Bar has a working copy constructor)

Foo f;
f.SetBar(*(new Bar));
const Bar* bar = &(f.GetBar());
f.SetBar(*(new Bar(bar)));
delete bar;

I have a situation similar to this (in code I didn't write) and when I debug at a breakpoint set on the "delete bar;" line, I see that

&f._bar == bar

My question is this: Why do &f._bar and bar point to the same block of memory, and if I leave out the "delete bar;", what are the consequences, from a memory management standpoint?

Many thanks!

like image 594
Jesse Stimpson Avatar asked Jan 21 '10 16:01

Jesse Stimpson


2 Answers

References cannot be "reseated", setBar() just copies the contents of bar to the object referenced by _bar.

If you need such a functionality use pointers instead. Also your usage example would be much simpler if you were just using pointers.

like image 81
sth Avatar answered Oct 07 '22 22:10

sth


The code you posted wouldn't compile, because references cannot be default constructed. Also, you seem to think you are reseating a reference, which you are not (see here). Instead, you are just copying objects over whatever _bar was referencing, so the value of:

&(f.GetBar())

never changes. You shouldn't delete _bar because you never owned it (or even really knew it was dynamically allocated) to begin with. That should be the responsibility of whoever "newed" it.

like image 39
Todd Gardner Avatar answered Oct 07 '22 22:10

Todd Gardner