Link reassignment

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 use of this class is as follows (suppose 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 like this (in the code I did not write), and when I debug the breakpoint set on the uninstall panel; I see what

 &f._bar == bar 

My question is this: why & f._bar and bar point to the same block of memory, and if I leave the β€œdelete panel”, what are the consequences in terms of memory management?

Many thanks!

+4
source share
2 answers

Links cannot be "re-closed", setBar() simply copies the contents of bar to the object referenced by _bar .

If you need this functionality, use pointers instead. In addition, your use case will be much simpler if you just use pointers.

+7
source

The code you submitted will not compile because the links cannot be built by default. Also, you seem to think that you are republishing a link that you are not (see here ). Instead, you simply copy the objects on top of any _bar links, so the value is:

 &(f.GetBar()) 

never changes. You should not delete _bar because you never owned it (or even really knew that it was dynamically allocated) to begin with. This should be the responsibility of the one who "invented" it.

+3
source

Source: https://habr.com/ru/post/1299018/


All Articles