开发者

Dangling reference. Alternatives for dangling pointers and references?

The following code produces dangling references:

int main()
{
  int *myArray = new int[2]{ 100, 200 };
  int &ref = myArray[0];
  delete[] myArray;
  cout << ref;  // Use of dangling reference.
}

I know I shouldn't delete the array but in a large program what if somebody deletes memory to which I have a reference? Can it be somehow assured that no one deletes the array?

What is the best开发者_StackOverflow中文版 strategy against dangling references and dangling pointers?


Don't delete the memory before you have finished with it.

Sounds stupid, but that's your only protection - properly understand who owns the memory behind each variable, and when it can safely be freed.

Smart pointers can help, but the above still applies.

It's possible some static analysis tools could identify the trivial case you have here, but even then that should be a second line of defence, with your first being discipline in memory management.


Keep them scoped properly:

int main(){
  int *myArray;
  myArray = new int[2]{ 100, 200 };
  {
    int& ref = myArray[0];
    // use the ref here
    cout<<ref;  \\no longer a dangling reference
  } // ref falls out of scope here
  delete[] myArray;
 }


Patient: Doctor, it hurts when I do this...

Doctor: Then stop doing it...

Do not release memory while having a reference to it.


EDIT

The only way to catch that is to debug, have good unit tests and run under valgrind, or run your program under valgrind.


All of the answers here have been "be careful!", and "use good programming practices!".
That's not a very satisfying answer. These problems have existed in C for 40+ years, and they are still common in any C++ project of significant size.

The biggest guidelines you'll hear people recommend are:

  • Use smart pointers
  • Use RAII

Both are true, but there is more you can do.

In 2015, the Standard C++ Foundation released the Guidelines Support Library.

You can write C++ programs that are statically type safe and have no resource leaks. You can do that without loss of performance and without limiting C++’s expressive power. This model for type- and resource-safe C++ has been implemented using a combination of ISO standard C++ language facilities, static analysis, and a tiny support library (written in ISO standard C++).

I recommend you use GSL's Owner<> with a static analysis tool.
That will guarantee safe behaviour.


Good programming practices. The compiler gives you more than enough rope to hang yourself with; it's your responsibility to make sure you don't.

In other words, if you don't take references to an array, and then delete it, then you won't have problems.

"But, what if it happens anyway?"

There's no simple answer, really. It's all about training, and knowing how to use the tools you're trying to use.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜