[Considerations for C/c++]_[Intermediate]_[delete class object pointers]

Source: Internet
Author: User
Scene:
1. C + + classes have constructors and destructors that are used to release resources when class objects are deleted (or when local variables are automatically destroyed).

2. C + + Class object Pointers in many cases need to be assigned to void* universal pointers to achieve the purpose of transmitting objects, but often this void* pointer is the source of memory leaks or program errors,

This is why C + + has a generic purpose, and it is also designed to eliminate this object uncertainty at compile time, avoiding delete or use errors.

OK, look at the code, what's wrong with the following code?


Test_class.cpp: Defines the entry point of the console application. #include "stdafx.h" #include <iostream>class a{public:a () {i = new int;} ~a () {Delete I;} int* i;}; Class B{public:b (void* data) {data_ = data;} ~b () {delete data_;} Void* Data_;}; Template <class t>class c{public:c (t* data) {data_ = data;} ~c () {delete data_;} T* Data_;}; void wrong () {A *a = new A (); b b (a); When a function returns, A's destructor does not call}void right () {A *a = new A (); C<a> c (A); When the function returns, A's destructor calls}int _tmain (int argc, _tchar* argv[]) {wrong (); Right (); return 0;}


[Considerations for C/c++]_[Intermediate]_[delete class object pointers]

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.