Exceptions of a C ++ rule

Source: Internet
Author: User

-- It is difficult to learn English and try to translate articles from a foreigner's blog. Start with a simple one. (Original author David)

 

Generally, you cannot modify a const type memory because it is not supported by technology. But there is a method (before the constructor runs) that allows you to do this. If 0 is passed to 80 char-sized const string parameters, the parameter becomes a variable (freeable) after it is destroyed in the destructor.

 

 # Include <iostream> </P> <p> class example <br/> {<br/> PRIVATE: <br/> const char * PTR; <br/> const bool freeable; </P> <p> Public: <br/> example (const char * optional): <br/> PTR (optional? Optional: New char [80]), <br/> freeable (optional? False: True) {}< br/> ~ Example () <br/>{< br/> If (freeable) <br/> Delete [] PTR; <br/>}</P> <p> void viewstate (char ID) <br/>{< br/> If (freeable) <br/> STD :: cout <id <"is freeable" <STD: Endl; <br/> else <br/> STD :: cout <id <"is not freeable" <STD: Endl; <br/>}< br/> }; </P> <p> int main (INT argc, char * argv []) <br/> {<br/> example S (0 ); <br/> example T ("Hello World"); <br/> S. viewstate ('s '); <br/> T. viewstate ('T'); <br/> return 0; <br/>}

We can see that S is freeable and T is not freeable.

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.