C and C + + code essence reading notes

Source: Internet
Author: User

Recently saw <<c and C + + code essence >>, design to C + + pointers, exception handling and other aspects, some of which self-think very good code, in the work is very worthy of reference.


1. Pointers to member functions

A

#include <iostream>using namespace Std;class c{    public:void f () {cout<< "c::f\n";} void G () {cout<< "c::g\n";}}; int main () {C c;void (c::* PMF) () =&c::f; (C.*PMF) ();p mf=&c::g; (C.*PMF) ();}

B

#include <iostream>using namespace Std;class object{public:void Retrieve () {cout<< "Object::retrieve"    <<endl;    } void Insert () {cout<< "Object::insert" <<endl;    } void Update () {cout<< "object::update" <<endl;    } void process (int choice);p rivate:typedef void (Object::* OMF) (); Static OMF Farray[3];};o BJECT::OMF object::farray[3]={&object::retrieve,&object::insert,&object::update};void Object:: Process (int choice) {if (0<=choice && choice<=2) (This->*farray[choice]) ();}    int Show_menu () {cout<< "1. retrieve\n"; cout<< "2.    Insert\n "; cout<< "3.    Update\n "; cout<< "4.    Quit\n ";    cout<< "Please input a num\n";    int n;    cin>>n; return n;}         int main () {int show_menu ();      Object o; for (;;)        {int Choice=show_menu ();        if (1<=choice && choice<=3) o.process (choice-1); else if (Choice==4) break; } return 0;}

2. Implement your own Assert macro

Assert.h#ifndef assert_h#define assert_hextern void _assert (char*, char*, long); #define ASSERT (COND) ((COND)? (void) 0: _assert (#cond, __file__, __line__)) #endif

By defining your own _assert method in the C file, you can easily use your own Assert macros:

#include <stdio.h> #include <stdlib.h> #include "assert.h" void _assert (char* cond, char* fname, long Lineno) { fprintf (stderr, "Assertion failed:%s, file%s, line%ld\n", cond, fname, Lineno); abort ();} int main () {assert (3>4); return 0;}
3. Use setjmp to define super-turn for exception handling

#include <stdio.h> #include <setjmp.h>jmp_buf jumper;void exception (); int  deal_exception (); main () {     int value = 0;     int i = 0;     Value = setjmp (jumper);     if (0 = = value) {         exception ();     }     else {         switch (value)         {case            1:                printf ("Solve exception[%d]\n", value);                break;            Case 2:                printf ("Solve exception[%d]\n", value);                break;            Case 3:                printf ("Solve exception[%d]\n", value);                break;           Default:                printf ("Solve exception[%d]\n", value);                Break;}}}    void exception () {    int _err_no = 3;    if (_err_no = = 3) {        printf ("exception[%d]\n", _err_no);        LONGJMP (jumper,_err_no);    }    return;}
4. Function Template Special

#include <iostream> #include <string.h> #include <string>using namespace Std;template<class t> size_t bytes (t& t) {cout<< "(using primary template) \ n"; return sizeof t;} size_t bytes (char*& t) {cout<< "(using char* overload) \ n"; return sizeof t;} template<>size_t bytes<wchar_t*> (wchar_t*& t) {cout<< "(using wchar_t* specialization) \ n"; return sizeof (Wcslen (t) +1); template<>size_t bytes<> (string& s) {cout<< "(using string explicit specialization) \ n"; return sizeof S;} template<>size_t bytes<float> (float& s) {cout<< "(using float explicit specialization) \ n"; return sizeof S;} int main () {int i;cout<< "bytes in I:" <<bytes (i) <<endl;const char* s= "Hello";cout<< "bytes in S:" <<bytes (s) <<endl;const wchar_t* w = (wchar_t*) "Goodbye";cout<< "bytes in W:" <<bytes (W) < <endl;string t;cout<< "bytes in T:" <<bytes (t) <<endl;float f;cout<<"Bytes in F:" <<bytes (f) <<endl;double d;cout<< "bytes in D:" <<bytes (d) <<endl;return 0;} 
Class template specificity

#include <iostream>using namespace Std;template<class T, Class U>class a{public:a () {cout<< "Primary Template\n ";}}; Template<class T, Class U>class a<t*, U>{public:a () {cout << "<T*,U> partial specialization\n";}}; Template<class T>class a<t, t>{public:a () {cout << "<T,T> partial specialization\n";}}; Template<class U>class A<int, u>{public:a () {cout << "<int,U> partial specialization\n";}}; int main () {a<char,int> A1; A<char*,int> A2; A<float,float> A3; A<int, float> A4;return 0;}
5. Methods for changing data members in a constant member function
A:This pointer de-const; B: Using mutable

#include <iostream>using namespace Std;class b{public:b () {state =0;pos=0;}    void f () const; void P () {cout<< "state=" <<state<< "pos=" <<POS<<ENDL;}    Private:int State; mutable int pos;}; void B::f () const{//((b*) this)->state=1;    Const_cast<b*> (This)->state=1; pos = 1;}    int main () {b b;    B.P ();    B.f ();    B.P (); return 0;}
6. Signal
#include <stdio.h> #include <signal.h>void ctrlc_handler (int sig), volatile sig_atomic_t ccount = 0;int Main ( {Char buf[100];if (signal (SIGINT, ctrlc_handler) = = Sig_err) {fputs ("Error Installing CTRLC handler\n", stderr);} while (gets (BUF)) {puts (BUF);} Signal (SIGINT, SIG_DFL);p rintf ("You pressed CTRLC%d times\n", ccount); return 0;} void Ctrlc_handler (int sig) {signal (sig, Ctrlc_handler); ++ccount;return;}
7. Exception handling: Resource allocation is the principle of initialization

/*exception:logic_errordomain_errorinvalid_argumentlength_errorout_of_rangeruntime_errorrange_erroroverflow_ errorunderflow_errorbad_allocbad_castbad_exceptionbad_typeid*/#include <cstdio> #include <memory> Using namespace Std;class file{    file* f;public:    file (const char* fname, const char* m ODE)     {        f = fopen (fname,mode);       & Nbsp;if (!f)             throw 1;    }    ~ File ()     {        if (f)         {             fclose (f);            puts ("File closed");        }    }};int main () {    void f (const char*);    try    {        //f ("File0.txt");        f ("file1.txt");    }     catch (int x)     {        printf ("Caught exception:%d\n", X) ;    }    return 0;} void f (const char* fname) {    auto_ptr<File> xp (New File (fname, "R"));    puts (" Processing file ... ");    throw 2;}
8. Non-standard Template library container

#include <valarray> #include <iostream> #include <algorithm>//#include <boost/foreach.hpp> Using namespace std;void print (double i) {    cout << i << "";} int main () {const int N = 10;const double Values[n] = {0,1,2,3,4,5,6,7,8,9};const valarray<double> v1 (values,n);//fo R_each (&values[0], &values[9], Ptr_fun (print));/*boost_foreach (double D, values) {cout<< D << Endl ;} */for_each (&v1[0], &v1[10], Ptr_fun (print)), Cout<<endl;cout << "min:" <<v1.min () << Endl;cout << "Max:" <<v1.max () <<endl;cout << "sum:" <<v1.sum () <<endl;return 0;}
9 Handling Memory allocation exceptions

A try{} catch (const bad_alloc& x)

B Set_new_handler

#include <iostream> #include <stdlib.h>using namespace std;inline void My_handler () {cout << "Memory Exhausted "<<endl;abort ();} int main () {Set_new_handler (My_handler); for (int i=0;; ++i) {(void) new Double[100];if ((i+1)% = = 0) cout << (i+1) << "allocations" <<ENDL;} return 0;}

Never run 9 on your computer!

C and C + + code essence reading notes

Related Article

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.