The delete in C + + does not place the operand in the 0_c language

Source: Internet
Author: User

Consider:

  Delete p;
  // ...
  Delete p;

If in ... Part does not relate to P, then the second "delete p;" Will be a serious mistake, because the implementation of C + + implementation, when referring to VC + + as the implementation of the C + + standard of specific tools can not effectively prevent this (unless through the informal means of prevention). Since delete 0 is defined as harmless, a simple solution would be to execute "deletep" wherever it is executed, followed by "P =". However, C + + does not guarantee this.

One reason is that the operand of delete does not require a left value (lvalue). Consider:

  Delete p+1;
  Delete f (x);

Here, the executed delete does not have a pointer that can be assigned to 0. These examples may be rare, but they do point out why it is not possible to guarantee that "any pointer to a deleted object is 0". A simple way to circumvent this rule is to have two pointers pointing to the same object:

  t* p = new T;
  t* q = p;
  Delete p;
  Delete q; Bad!

C + + explicitly allows the delete operation to place the operand left at 0, and I once hoped that the C + + implementation would do this, but this thought does not seem to be prevalent in the implementation of C + +.

If you think that pointer 0 is important, consider using a destroyed function:

  Template<class t> inline void Destroy (t*& p) {delete p; p = 0;}

Consider that this is another reason why you need to rely on the container, handle, and so on of the standard library to minimize the explicit invocation of new and delete.

Note that passing pointers by reference (to allow pointers to be set to 0) has an additional benefit to prevent destroy () from being invoked on the right (rvalue):

  int* f ();
  int* p;
  // ...
  Destroy (f ()); Error: A non-const reference should be used to pass the right value
  destroy (p+1);//Error: The right value should be passed with a very strong (non-const) reference

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.