5

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!

2
  • As written, the code doesn't compile. Foo does not have a default constructor. Commented Jan 21, 2010 at 16:36
  • 11
    You should hit whoever did write the code very hard over the head - references are not intended to be substitutes for pointers. Commented Jan 21, 2010 at 16:38

2 Answers 2

8

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.

Sign up to request clarification or add additional context in comments.

Comments

3

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.