C ++ usage experience

Source: Internet
Author: User
Tags posix microsoft c

1 STD: string cannot be compared directly with "" (both false), and can only be compared with getlength () = 0.
It occupies 4x4 bytes in the structure. The second 4 bytes is the buffer pointer, and the third 4 bytes is the length.

2. When the push structure and other types are imported into the STL container, the copy constructor must be used (the default copy constructor is a bit copy); otherwise, compilation errors such as 2558 will occur.
Java C # Place all objects on the stack. c ++ is not

3. the subtraction of the unsigned number does not show a negative number.

4 0x2 & 0x2 = 0x2 the front must be enclosed in brackets (priority issue)

5 The list iterator can only be ++ I, and cannot be I + = 2 (Compilation and translation are not successful). The vector reloads [], and the list does not

6 iterator generally has! ==<<=>>=+-Heavy load

7 Relationship Between Stack, heap and static Zone
Stack grows from high to low.
The static zone (such as global variables and static variables) is in the lowest memory zone.
Above the static zone is the heap, increasing from low to high.

8. containers cannot be inserted or deleted during cyclic iterator.
Vector can be deleted in a loop in the form of erase (it --).
Map cannot connect to erase (it --). An error occurs in the loop header when the last one is deleted. You can copy a temporary map to loop (if the source map is small)

9. Be careful about else suspension issues (else only matches the nearest if)

10. the whole migration may be performed when inserting elements in a vector. In erase, the entire element is migrated to a position (the header remains unchanged), and the content of the additional space remains unchanged.
Iterator is a pointer.

11 polymorphism during compilation: overload and template
Polymorphism during running: virtual function
(Multimethod is also a type of polymorphism in runtime. You can determine the correct method call when multiple objects are involved, such as void doubledispatch (shape & LHS, shape & RHs)
When there are many child classes in shape, it will be very troublesome if you perform dynamic conversion in the function to determine the specific child type)

When writing the code, it cannot be determined whether the base class function or the derived class function is called, so it becomes a "virtual" function. The virtual function can only achieve polymorphism with pointers or references (that is, base A; A. Foo (); is not polymorphism );
Usage principle of virtual table: the compiler converts a-> Foo () to a virtual table call (a-> vptr [1]). thus, the function can be called at runtime ("Deferred Association" or "Dynamic Association").

Pure virtual function: Virtual void Foo () = 0; // = 0 indicates that a virtual function is a pure virtual function, which cannot be instantiated.

When a class's virtual functions are called in its own constructor and destructor, they become common functions.

12 modern c ++ design = 'generic patterns' or 'pattern'
Type-list is the basis.
Generalized functors: functor is a delayed call to a function, a functor, or a member function. It stores the callee and exposes operator () for invoking it.
Multimethods are generalized virtual functions can be used to distribute runtime methods among multiple classes (the original virtual function can only be between the same class ).

13 suggestions in C ++ (relative to C)
A uses const or enum to replace macros. Note that when defining a String constant, it is best to const char * const authorname = "Scott Meyers"; point to the constant pointer.
B can declare the variable as needed for immediate initialization (C puts all the variables before the function)
C replace malloc with new
D. Do not use void *. Generally, forced type conversion means a design error. static_cast <int *> (malloc (100) (related type conversion), reinterprete_cast <io_device *> (0xff00) (unrelated type conversion, the least secure, or even no matter whether the converted pointer is valid), the runtime type conversion check dynamic_cast <t *> (P) (this function can be used to test the conversion of class pointers. For example, if the parent class pointer is down during polymorphism, static_cast does not perform this check)
E. Do not use arrays and C-style strings. Use STD: vector and STD: string.
F to ensure compatibility between systems, the int type is not used (because the length of storage bytes varies between systems, for example, the int type in a 16-bit system is 2 bytes ), long or short type should be used

14 two types of STL containers: sequence and assosiative)
15 c str function to STD: String function ing
Strcpy =
Strncpy = DeST. substr (0, n)
Strcat append function or + =
Strlen length Function
Strstr find (the initial position starts from 0 and cannot be found as-1)
Strcmp compare (const basic_string & Str) function (returns 0 if it is equal to, and-1 if it is not equal)
Strncmp compare (size_type P0, size_type N0, const basic_string & Str) (compare P0 with N0 elements and Str)
Compare (size_type P0, size_type N0, const basic_string & STR, size_type POs, size_type N) (STR also takes only n elements from the POs)

16 has been used in the library, and later does not need to, in addition to remove include and so on, but also re-Complete Compilation, or still reported that the XXX. Lib cannot be found

17 even if the Delimiter is a value assignment statement, it is not atomic because of rmw (read from the memory bus, modify the CPU, write back to the memory, and unlock the structure after reading the memory)

In 18 C ++, stack allocation is slow because you need to find available "holes ". Java uses heap allocation, but it uses the "conveyor belt" format and is always distributed later. Therefore, heap allocation is faster. The simplest GC garbage collection solution is reference counting.

19 because map and set are stored in the sorting structure (red and black trees), sort is no longer provided. If you want to do so, you must merge them into the vector and so on.

Top 20 pointer = intelligent pointer auto_ptr (C ++ standard, but very poor, cannot be put into the container, so we recommend using the smart pointer in boost or Loki)
Weak pointer = Traditional pointer

21 main differences between malloc/free and new/delete: The function/operator new/delete calls the constructor and the Destructor (malloc/free does not)
The memory pointer from malloc is void *, so you need to convert it yourself. It can only be used for internal data types.

22. Thread Synchronization Method
Critical section: Only one thread can enter the code segment at a time. It is mainly used to implement synchronization between threads, but when using it, note that this object must be created outside the thread where the critical object is synchronized (usually a critical object is created in the main thread ).
Mutex: It can be synchronized across processes and named after strings.
Semaphores: Special mutex, but the number of managed resources can be greater than 1

23 extern keyword
In order to realize the mixed programming of C and C ++, C ++ provides the C connection to exchange the specified symbol extern "c" to solve the name matching problem, after the extern "C" is added before the function declaration, the compiler will compile the function as _ Foo in the C language, so that the C ++ function can be called in the C language.
The extern keyword declares a variable or function and specifies that it has external linkage (its name is visible from files other than the one in which it's defined ). when modifying a variable, extern specifies that the variable has static duration (it is allocated when the program begins and deallocated when the program ends ). the variable or function may be defined in another source file, or later in the same file. in C ++, when used with a string, extern specifies that the linkage conventions of another language are being used for the declarator (s ).
"C" is the only other language specifier currently supported by Microsoft C/C ++.
Example of declaring an external link function:
Extern "C" int printf (const char *,...);

Extern "C"
{
Int getchar (void );
Int putchar (INT );
}

24. Put the const behind the function.
This function cannot change the class member variables in the function body.

25 static variables defined in the function are also fixed and initialized during compilation (that is, they should be stored in the Global static storage area)

Win32 layout exists in 26G
0-4 m reserved for DoS
4 m-2g private program
2G-3G program sharing
3G-4g system Zone

27 The Standard C/C ++ library does not have the ITOA function. You can use the string in boost to convert the lexical_cast
Using STD: string;
Const double D = 123.12;
String S = boost: lexical_cast <string> (d); // an error occurs when an exception is thrown.

18 Software Reuse
1) DLL-Level Reuse: the calling of the DLL stores the location of the function to be called, which causes the DLL to have version matching and directly causes the occurrence of the DLL hell (the DLL itself carries independent functions and data, this is quite independent, and it is easy to implement error isolation after program Integration), "unable to locate program Input Point XXX at XXX. DLL"
2) COM is a binary standard and only accesses the public memory structure of COM externally. Therefore, the differences between different programming languages and application environments can be ignored, solved the issue of re-compilation and release.
3) component-Level Reuse
4) Reuse of frameworks: Reuse of Design and Analysis

19 if the inheritance relationship between the two classes is private, the compiler generally does not convert the derived class Object (such as student) to the Base Class Object (such as person); if the class D is private to Class B, this is because you want to use some existing code in Class B, rather than the conceptual relationship between the object of type B and the object of Type D.

20 volatile tells the compiler that the variable may be changed by a non-statement. Do not make any assumptions about operations such as writing the same value continuously during optimization (that is, do not take them for granted );
Int volatile nvint;
For example, the pointer to the device register volatile unsigned short * pp2ltch = (unsigned short *) 0x7200005e; this pointer is easy to lose, it should be understood that the Register value pointed to by this pointer is easy to lose.

21 ActiveX compared with other COM components, the most comfortable thing is that attributes and events can be directly adjusted in the "attribute" panel, which is generally the OCX control, while the general COM component is provided in the form of DLL

22. for policy-oriented programming, major classes are divided into many classes with a single function (one aspect ?)
A policy defines a class interface or a class template interface. The interface consists of one or all of the following: inner Type Definitions, member functions, and member variables.

23. Several (6) Basic macros defined by ansi c:
_ Timestamp _ file _ line _ (each project or module should have a unified commissioning switch or printing function, for example, with a file name and line number)

24 DLL Problems
"All objects created by the code of the function in d l are owned by the calling thread, while D l never owns anything"
"D l can contain dialog box templates, strings, icons, bitmaps, and other resources. Generally, d l does not support code for processing message loops or creating windows"

Two DLL Connection Methods:
1) Implicit join:
Implicit is a common method (the Lib file must be referenced during the link so that the source code of the application can only reference the symbols contained in d l)
"If the linked program finds that the source code module of d l outputs at least one function or variable, the linked program also generates a. l I B file. This. l I B file is small because it does not contain any function or variable. It only lists the symbolic names of all output functions and variables. "
2) display connection:
"DLL lib files are not required because the output symbols are not directly referenced. The. exe file does not contain an input table. "
"A thread calls the loadlibrary (Ex) function to load the DLL to the address space of the process. At this time, the thread can call getprocaddress to indirectly reference the DLL output symbol. "

25 fundamental to com are these concepts:

Interfaces: The mechanism through which an object exposes its functionality.
Iunknown: the basic interface on which all others are based. It implements the reference counting and interface querying mechanisms running through COM.
Reference counting: The technique by which an object (or, strictly, an interface) decides when it is no longer being used and is therefore free to remove itself.
QueryInterface: the method used to query an object for a given interface.
Stored aling: The mechanism that enables objects to be used into SS thread, process, and network boundaries, allowing for location independence.
Aggregation: a way in which one object can make use of another.

26 ATL is the Active Template Library, a set of template-Based C ++ classes with which you can easily create small, fast Component Object Model (COM) objects. it has special support for key com features including: stock implementations of iunknown, iclassfactory, locations and idispatch; dual interfaces; standard com enumerator interfaces; connection points; tear-off interfaces; and ActiveX controls.

ATL is a set of C ++ libraries that implement COM/ActiveX in the VC ++ environment (provided as a template ).

27 ActiveX:
A set of technologies that enables software components to interact with one another in a networked environment, regardless of the language in which they were created. ActiveX is built on the Component Object Model (COM ).

28 to prevent the sender from being permanently suspended by the sendmessage function (for example, if the receiver fails to handle the error), you can use sendmessagetimeout.

29 Data Alignment is not part of the memory structure of the operating system, but part of the c p u structure.
When the c p u accesses the correct aligned data, it runs most efficiently. When the memory address of the Data modulus is 0, the data is aligned. For example, the w o r d value should always start from the address divided by 2, and the d w o r d value should always start from the address divided by 4.
# Pragma pack (2)
....
# Pragma pack () // Restore Default

28 The initialization formula must be used instead of the place initialized in the constructor.
1) if the class has an inheritance relationship, the derived class must call the base class constructor in its initialization table.
2) the const constant of the class can only be initialized in the initialization table, because it cannot be initialized using the value Assignment Method in the function body.

29. Dual-interface iunknown and idispatch of COM (iunknown is required)
Methods In vtable order
Iunknown methods:
QueryInterface returns pointers to supported interfaces.
Addref increments the reference count.
Release decrements the reference count.

Idispatch methods:
Gettypeinfocount retrieves the number of type information interfaces.
Gettypeinfo retrieves the type information for an object.
Getidsofnames maps a single member and an optional set of argument names to a corresponding set of integer DISPIDs.
Invoke provides access to properties and methods exposed by an object.

30 when the C ++ class has an object member, the default copy constructor is no longer provided, and an error is reported during compilation. You can change it to a pointer and create and release it in the constructor and destructor.

31 each new thread attributes es its own stack space, consisting of both committed and reserved memory. By default, each thread uses 1 MB of reserved memory, and one page of committed memory.

32 + + front and rear Effects
AA = 0;
J = (AA ++) + AA; // J = 0, AA = 1
AA = 0;
J = (AA ++) + AA ++; // J = 0, AA = 2
AA = 0;
J = (AA ++) + (++ aa); // J = 2, AA = 2

33 comparison of arrays and pointers
Arrays are either created in static storage areas (for storing global and static variables) (such as global arrays) or on stacks. The array name corresponds to (rather than pointing to) a piece of memory, and its address and capacity remain unchanged during the lifetime, only the content of the array can be changed.
Char A [] = "hello"; // note that sizeof (A) = 6 (actual length plus 1), the sizeof character array is different from the sizeof pointer, char * P; sizeof (p) = 4; simple char AAA []; not compiled
A [0] = 'X ';
Cout <A <Endl;
Char B [10];
Strcpy (B, A); // cannot use B = A; this is not compiled, Report "cannot convert from 'Char [6] 'to 'Char [10]'"
Char * P = "world"; // note that P points to a constant string
P [0] = 'X'; // This error cannot be found by the compiler and is reported only during runtime. In addition, sizeof (A) = 6 and sizeof (p) = 4

34 Windows and Linux
Creation process: CreateProcess and fork
Thread: createthread and pthread_create
Thread Synchronization: waitforsingleobject () and waitformultipleobjects () and pthread_join ()
 
35 keyword about protected
Protected keyword specifies that those members are accessible only from member functions and Friends of the class and its derived classes. this applies to all Members declared up to the next access specifier or the end of the class.

When preceding the name of a base class, the protected keyword specifies that the public and protected members of the base class are protected members of the derived class.

Default access of members in a class is private. default access of members in a structure or union is public.

Port 36 (supported only after Windows 2000 or XP)
Createiocompletionport (create a complete port) getqueuedcompletionstatus (obtain an event on a completed port) postqueuedcompletionstatus (actively send an event to a completed port)
Implementation of asynchronous Io on two platforms:
Windows: The Windows readfile () and writefile () system functions can either perform synchronous I/O or initiate an overlapped I/O operation.

POSIX.: The POSIX aio_read () and aio_write () functions initiate asynchronous read and write operations, respectively. these functions are separate from the read () and write () (and sockets Recv () and send ()) functions that are used in Ace's IPC wrapper facade classes (see chapter 3 in C ++ npv1 ).

First, understand what is a signal/non-signal state, what is a wait function, what is a side effect of a successful wait, and what is a thread suspension?

37 apachemonitor in Apache source code can be easily converted into a Windows Graphics Management Platform for other services. The XML analysis module can also be directly embedded into other applications.
Note: When compiling Apache, put the include directory of the SDK in front (VC option)

38. The character constants in the function are in the stack memory, not the global storage zone.
Char * getmemory (void)
{
Char P [] = "hello"; // note that if it is char * P = "hello", the memory pointed by P goes to the global constant area (the memory in this area cannot be rewritten, after the function is returned, the hello in the global zone is still present (even if other functions are called to cause stack changes)
Int I = sizeof (p); // same as = 6
Return P;
}
Void cmsgbox2dlg: onbutton11 ()
{
Char * P = getmemory ();
Char PP [10];
Int I = 0;
I ++;
Memcpy (PP, P, 6); // as long as other functions are called here, the content of P becomes garbled, indicating that the form of char P [] P exists in the stack zone.
Afxmessagebox (PP );
}

39 macro side effects
# Define min (A, B) (a) <= (B )? (A): (B ))

Int A = 2, B = 3;
Int fff = min (A ++, B );
// A = 4, fff = 3

Int A = 4, B = 3;
Int fff = min (A ++, B );
// A = 5, fff = 3

40 references and pointers
The original reference must point to an object, but if someone writes it like this, it may produce unpredictable results.
Char * Pc = 0; // set pointer to null
Char & rc = * PC; // make reference refer
// Dereferenced NULL pointer

41 whether it is int A [10]; or int * A; A = new int [7];
* (A + 7) is always equivalent to a [7]

42. Why must the parameters of the copy function be referenced?
If this is not the case, the parameter itself will also be a copy (and also a bit copy)

43 C ++ does not have a good way to return class objects (returning pointers, instances, and references all have their own defects). Some compilers have proposed a work und.

44 cobject is the principal base class for the Microsoft Foundation Class Library. it serves as the root not only for library classes such as cfile and coblist, but also for the classes that you write. cobject provides basic services, including
1) serialization support
2) Run-Time class information
3) object diagnostic output
4) compatibility with collection classes
Note that cobject does not support multiple inheritance.
In addition, some MFC classes are not inherited from cobject, such as some tool classes: cstring and ctime.

Reference: http://blog.csdn.net/stephenxu111/archive/2008/05/09/2424520.aspx

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.