4-16 written test

Source: Internet
Author: User

I,

Char STR [] = "ABCD"; cout <sizeof (STR) <Endl; // Answer: 5. Because there is a '\ 0' wchar _ t wstr [] = "ABCD"; cout <sizeof (wstr) <Endl; // Answer: 10. In wchar_t, '\ 0' is also two bytes. Wchar_t cannot be used in the G ++ compiling environment of Linux. The cause is unknown: char * P = "ABCD"; cout <sizeof (p) <Endl; // Answer: 4. Because p is the pointer void * A = (char *) malloc (100); cout <sizeof (a) <Endl; // Answer: 4. Because a is a pointer

II,

# Define Max 3 + 2 cout <Max * max <Endl; // Answer: 11. 3 + 2*3 + 2 = 11

3. Why should I use "extern C" when calling a function compiled by the C compiler in C ++ "?

A:

Extern is a keyword in C/C ++ that indicates the range (visibility) of functions and global variables. This keyword tells the compiler, the declared functions and variables can be used in this module or other modules. In general, the functions and global variables referenced by this module to other modules are declared with the keyword include in the module header file. For example, if Module B wants to reference the global variables and functions defined in module A, it only needs to include the header file of module. In this way, when Module B calls a function in module A, although Module B cannot find the function in the compilation phase, no error is reported; it will find this function from the target Code Compiled by module A in the connection phase. As an object-oriented language, C ++ supports function overloading, while Procedural Language C does not. The name of the function in the symbol library after being compiled by C ++ is different from that in the C language. For example, assume that the prototype of a function is void Foo (int x, int y). After the function is compiled by the C compiler, its name in the symbol library is _ Foo, the C ++ compiler generates names such as _ foo_int_int (different compilers may generate different names, but all adopt the same mechanism, the new name is called "mangled name "). A name such as _ foo_int_int contains the function name, number of function parameters, and type information. c ++ relies on this mechanism to implement function overloading. For example, in C ++, the void Foo (int x, int y) and void Foo (int x, float y) functions generate different symbols, the latter is _ foo_int_float. Similarly, variables in C ++ support both local variables and class member variables and global variables. The class member variables of the program written by the user may have the same name as the global variables, which are distinguished. In essence, the compiler uses a unique name for the variables in the class when compiling, similar to the function processing. This name is different from the global variable name with the same name in the user program. Extern "C" is a linkage declaration. Variables and functions modified by extern "C" are compiled and connected in C language. (1) The connection method when the extern "C" statement is not added is assumed in C ++. the header file of module A is as follows: // module A header file modulea. hint Foo (int x, int y); reference this function in Module B: // Module B implementation file moduleb. CPP # include "modulea. H "Foo (2, 3); in the connection phase, the connector will generate the target file modulea from module. search for symbols like _ foo_int_int in OBJ! (2) After the extern "C" declaration is added to the compilation and connection method and the extern "C" declaration, the header file of module A is changed to: // module A header file modulea. hextern "C" int Foo (int x, int y); In Module B's implementation file, Foo (2, 3) is still called. The result is: (1) when module A compiles the foo target code, it does not perform special processing on its name and uses the C language. (2) The connector searches for Foo (2, 3) for the target code of Module B) during the call, you are looking for the unmodified symbol name _ Foo. If the function in module A declares that foo is of the extern "C" type, and Module B contains the extern int Foo (INT X, int y ), module B cannot find the function in module A, and vice versa. Therefore, we can summarize the true purpose of the statement "extern" C "in one sentence: to implement mixed programming of C ++ and C and other languages. Extern "C" common usage tips and usage: (1) reference functions and variables in C language in C ++, in the header file containing C language (assumed as cexample. h), the following processing is required: extern "C" {# include "cexample. H "} in the header file of C language, the external function can only be specified as the extern type. The C language does not support the extern" C "declaration. when the c file contains extern "C", a compilation syntax error occurs. If C ++ calls a. dll written in C language, when it includes the header file of. dll or the declared interface function, it should add extern "C "{}. (2) When referencing functions and variables in C ++ in C, the header file of C ++ needs to add extern "C ", however, you cannot directly reference this header file that declares extern "C" in C. You should only declare the extern "C" function defined in C ++ as the extern type.

4. What is the difference between stack and stack? Where are global variables, static variables, and constants stored? Char * P = "ABC";, where is "ABC" stored?

Record, to be summarized 2

"ABC" is stored in the text constant area.

5. What is the difference between sendmessage () and postmessage? What is the difference between getmessage () and peekmessage?

Http://blog.csdn.net/xt_xiaotian? Viewmode = Contents

1. the running mechanism of sendmessage and postmessage: The sendmessage function sends a message. Only sendmessage is returned after the message processing is complete. A little deeper, the sendmessage is returned after the window processing function returns. Postmessage can be understood as a postmessage function that sends a message and returns immediately without waiting for the message to be processed. A little deeper, postmessage only sends the message, and does not care if the message is sent or not. As long as the message is sent, it is immediately returned. This is sufficient for programmers who write General Windows programs. 2. The running details of sendmessage and postmessage are as follows: The sendmessage function sends the specified message to a window or windows. it callthe window procedure for the specified window and does not return until the window procedure has processed the message. the sendmessage function sends the specified message to the window. It calls the window processing function of a specific window and does not return immediately until the window processing function processes the message. Let's take a look at the postmessage explanation: the postmessage function places (posts) a message in the message queue associated with the thread that created the specified window and returns without waiting for the thread to process the message. the postmessage function puts a message into the thread related to the Message Queue that created the window, and immediately returns the message without waiting for the thread to process the message. After carefully reading the msdn explanation, we learned that sendmessage is indeed sending a message, and then waiting for the response to be completed, but the method for sending a message is to directly call the message processing function (namely, the wndproc function ), according to the function call rules, sendmessage is returned only after the message processing function is returned. However, postmessage does not send a message. postmessage puts the message into the message queue and immediately returns the message. postmessage does not know when the message is processed, at this time, only the message loop knows when the message to be postmessage is processed.

Getmessage (lpmsg, hwnd, uint wmsgfiltermin, uint rows) peekmessage (lpmsg, hwnd, uint wmsgfiltermin, uint wmsgfiltermax, uint wremovemsg) the wremovemsg parameter specifies the message retrieval method. If it is set to pm_noremove, the message will not be removed from the message queue. If it is set to pm_remove, the message will be removed from the message queue. The two functions have the following two differences: 1. getmessage will not be returned until there is a suitable message, while peekmessage is just a glimpse of the message queue. 2. getmessage will delete the message from the queue, while peekmessage can set the last parameter wremovemsg to determine whether to keep the message in the queue. In Windows, getmessage and peekmessage execute the same code. The biggest difference between the two is that no message is returned to the application. In this case, peekmessage returns a null value to the application, and getmessage will sleep the application at this time.

6. For example, which synchronization objects (or locks) are used in windows and under what circumstances?

Http://www.cppblog.com/sherrylso/archive/2007/07/22/28585.html

On the Windows platform, it is used to protect synchronization between multiple threads (including processes). There are basically several types of protection mechanisms: 1) critical section object (critical section) 2) event object (Event) 3) mutex object (mutex) 4) semaphore object (semaphore ). The focus of this article is to summarize some obvious behavior characteristics of these synchronous protection mechanisms. The behavior features discussed below are a general description of the synchronous protection mechanism between concurrent threads and threads. This article uses Windows as a typical example. Based on these behavioral features, we will classify the four synchronization objects mentioned in this article. In addition, the four synchronization objects are called "locks" for further discussion. First, protection and synchronization. It should be emphasized that protection and synchronization are two different concepts. We often mix these two concepts. Protection refers to the protection of shared resources in a multi-threaded environment. In most cases, a shared resource is a block of memory, which will be accessed and modified by many threads. Synchronization focuses more on the collaboration between threads, and collaboration must be supported by synchronization. Based on this nature, we can see that the nature of the critical section object emphasizes protection, while the event object, mutex object, and semaphore object emphasize synchronization. However, such a difference is only a conceptual difference, which will not affect the program itself. 2. Lock wait timeout when developing concurrent multi-entry/thread programs, in order to avoid problems such as deadlocks, the concept of "Wait For timeout" is introduced, that is, when a thread needs to obtain a lock to execute some code, it can set a timeout value in the waiting lock. If the lock cannot be obtained within the specified time (timeout value), it can choose to give up the right to execute the code segment, so as to avoid deadlock to a certain extent. This is the basic meaning of lock wait timeout. Based on this row as the feature, we will divide the above four synchronization objects: The critical section object cannot be set to wait for timeout, while the other three objects can be set to wait for timeout. In this regard, when using the critical section object, it is easy to cause a deadlock because the wait timeout cannot be set while waiting to enter the key code segment. Third, the thread lock and process lock here refer to the thread lock which is visible only to all threads of a process, the process lock means that the lock can be accessed by different processes and can be used for synchronization and mutual exclusion between processes. Of course, the process lock can still be used for synchronization and mutex between different threads of the same process. The process lock concept is greater than the thread lock. Based on this feature, the critical section object is a thread lock, and the other three objects are a process lock. This is essentially an analysis. The critical section object is a thread synchronization method in the user mode, and the other three objects are kernel objects. The adaptability of the kernel object mechanism is far better than that of the user mode mechanism. In fact, the only drawback of the kernel object mechanism is that it is slow, because when calling the kernel object mechanism, it must be switched from the user mode to the kernel mode. Such a conversion requires a high price and is a very time-consuming operation. On the X86 platform, this round-trip requires 1000 CPU cycles (this does not include code that runs the kernel mode ). Of course, it should be noted that the use of the critical section object does not mean that the thread will not be in the core State for execution. When a thread tries to enter a key code segment owned by another thread, the thread enters the waiting state. This means that the thread must change from user State to core state. (To improve the performance of this aspect, Microsoft incorporated the concept of loop lock into the critical section object. This thread can selectively not enter the core State wait. for details, see msdn) 4. Recursive characteristics of a lock the so-called recursive lock refers to the desire to obtain the lock again recursively when a thread has a Synchronous lock. if this operation does not block the execution of the current thread, the lock is called a recursive lock. recursive locks are mainly proposed in the concept of "protection". The locks under the concept of "protection" include critical section objects and mutext objects. these two locks are recursive locks on Windows platforms. Note: The call thread must release the recursive lock several times to obtain the recursive lock. Fifth, read/write locks allow efficient concurrent access to shared resources in a multi-threaded environment. For a shared resource, multiple threads can obtain the read lock and read the shared resource in a shared manner. At the same time, only one thread can have a write lock to change the shared resource. This is the concept of read/write locks. Unfortunately, there is no such read/write lock on windows. You need to implement it on your own.

  Support timeout Process lock Recursive lock Read/write lock
Critical section object No No Yes N/
Event object Yes Yes N/ N/
Mutex object Yes Yes Yes N/
Semaphore object Yes Yes N/ N/

7. What is the relationship between the process and thread in windows? Can I create a window in a thread?

Http://www.blogjava.net/chalmers/archive/2011/03/31/347358.html

A process is the unit in which resources are allocated by the system. Each process corresponds to an active program. When a process is activated, the operating system allocates system resources, including memory, I/O, and CPU, for execution. A thread is the unit of CPU allocation time. Each thread corresponds to a function in the process, that is, a code segment in the memory. When multiple threads are executed, the CPU allocates time based on their priority, enable them to complete their functions. Generally, a process consists of at least one thread, one main thread, and other threads. Multiple Threads aim to share the CPU time slice to complete parallel tasks. 1. The basic unit of scheduling and dispatching by the scheduler. A process is the basic unit of resource ownership. 2. concurrent processes can be executed concurrently, and multiple threads in a process can also be executed concurrently. 3. A Resource-owning process is an independent unit of resources. A thread itself does not own system resources (or has a few indispensable resources), but it can access the resources of its processes. 4. when a system overhead creates or revokes a process, the system allocates or recycles resources for it, such as memory space and I/O devices, the overhead of the OS is significantly greater than the overhead when the thread is created or withdrawn; the overhead of process switching is much higher than the overhead of thread switching. In fact, the thread runs but the process does not run. The only way for two processes to obtain dedicated data or memory is to share the memory block through the Protocol. This is a collaboration policy. The above explanation is the reason. The above is the basic information column we can see in the process tab of the task manager.
Window can be created in the thread

8. What are the methods for inter-process communication?

Http://blog.csdn.net/shiqz/article/details/5862936

1. Memory-mapped files allows the Process to Treat the file content as a piece of memory in the process address range. Therefore, the process does not need to use file I/O operations, and can read and modify the file content with simple pointer operations. Win32 API allows multiple processes to access the same file ing object. Each process receives memory pointers in its own address space. By using these pointers, different processes can read or modify the file content to share data in the file. There are three ways for an application to share a file ing object with multiple processes. (1) Inheritance: the first process establishes a file ing object, and its child process inherits the handle of the object. (2) named file ing: when creating a file ing object, the first process can specify a name for the object (which may be different from the file name ). The second process can use this name to open the file ing object. In addition, the first process can also pass the name to the second process through some other IPC Mechanisms (such as famous pipelines and email slots. (3) handle replication: the first process establishes a file ing object, and then passes the object handle to the second process through other IPC Mechanisms (such as famous pipelines and email slots. The second process copies the handle to obtain the access permission for the ing object of the file. File ing is a very effective way to share data among multiple processes and provides better security. However, file ing can only be used between processes on the local machine and not on the network. Developers must also control the synchronization between processes. 2. Shared Memory in Win32 API is a special case of file ing. When creating a file ing object, the process uses 0xffffffff to replace the handle, which means that the corresponding file ing object accesses the memory from the file on the operating system page, other processes can open the file ing object to access the memory block. Because shared memory is implemented by file ing, it also has good security and can only run between processes on the same computer. 3. An anonymous pipeline (PIPE) is a communication channel with two endpoints: a process with one end handle can communicate with a process with the other end handle. The pipeline can be one-way-one end is read-only, and the other end point is write-only. It can also be two-way. The two ends of a pipeline are both readable and writable. An anonymous pipeline (anonymous pipe) is a one-way channel that transfers data between a parent process and a child process, or between two child processes of the same parent process. Generally, the parent process creates an MPS queue, and then the child process to communicate inherits the read endpoint handle or write endpoint handle of the channel, and then implements communication. The parent process can also create two or more sub-processes that inherit anonymous pipeline read and write handles. These sub-processes can communicate directly using pipelines without passing through the parent process. An anonymous pipeline is an effective method for implementing sub-process standard I/O redirection on a single machine. It cannot be used online or between two unrelated processes. 4. Named pipeline named pipeline (Named Pipe) is a one-way or two-way pipeline for communication between server processes and one or more customer processes. Unlike an anonymous pipe, a named pipe can be used between unrelated processes and different computers. When the server creates a named pipe, a name is specified for it, any process can use this name to open the other end of the pipeline and communicate with the server process based on the given permissions. The named pipeline provides a relatively simple programming interface, making it easier to transmit data over the network than to communicate with two processes on the same computer. However, it cannot communicate with multiple processes at the same time. 5. mailslots provides one-way communication capabilities between processes. Any process can establish a mail slot as a mail slot server. Other processes, called mail slot customers, can send messages to the mail slot server process by the name of the mail slot. The incoming message is kept in the mail slot until the server process reads it. A process can be either a mail slot server or a mail slot customer. Therefore, multiple mail slots can be established to implement bidirectional communication between processes. You can use the mail slot to send messages to the mail slots on the local computer, the mail slots on other computers, or the mail slots with the same name on all computers in the specified network area. The length of a message for a broadcast communication cannot exceed 400 bytes. The length of a non-broadcast message is limited by the maximum message length specified by the mail slot server. The mail slot is similar to the named pipe, but it transmits data through unreliable datagram (such as UDP packets in TCP/IP protocol, once a network error occurs, messages cannot be correctly received, while the named pipe transmits data based on reliable connections. However, the mail slot provides simplified programming interfaces and the ability to broadcast messages to all computers in the specified network area. Therefore, the mail slot is another option for applications to send and receive messages. 6. The clipboard (clipped Board) is essentially a group of functions and messages used to transmit data in Win32 APIs. It provides an intermediary for data sharing between Windows applications, the cut (copy)-paste mechanism established in Windows provides a shortcut for different applications to share data in different formats. When a user performs a cut or copy operation in an application, the application puts the selected data in one or more formats on the clipboard. Then, any other application can pick up data from the clipboard and select a suitable format from the given format. The clipboard is a very loose exchange medium that supports any data format. Each format is identified by an unsigned integer in a standard (predefined) clipboard format, this value is a constant defined by Win32 API. For non-standard formats, you can use the register clipboard format function to register it as the new clipboard format. You only need to use the clipboard to exchange data in the same format or convert the data to a certain format. However, the clipboard can only be used in Windows-based programs and cannot be used on the network. 7. Dynamic Data Exchange (DDE) is a form of inter-process communication in which data is exchanged between applications in the shared content. Applications can use DDE for one-time data transmission, or dynamically exchange data between applications by sending update values when new data appears. Like clipboard, DDE supports both standard data formats (such as text and bitmap) and custom data formats. However, their data transmission mechanisms are different. One obvious difference is that clipboard operations are almost always used as a one-time response to user-specified operations-for example, selecting the paste command from the menu. Although DDE can also be started by the user, it continues to play a role without further user intervention. DDE has three data exchange methods: (1) Cold Chain: data exchange is a one-time data transmission, the same as the clipboard. (2) temperature chain: when data is exchanged, the server notifies the customer, and then the customer must request new data. (3) Hot chain: when data is exchanged, the server automatically sends data to the customer. DDE exchange can occur between applications of different computers in a single machine or network. Developers can also define custom DDE data formats for specific IPC between applications, which have more closely coupled communication requirements. Most Windows-based applications support DDE. 8. Object connection and embedding applications use object connection and Embedding (OLE) technology to manage composite documents (documents composed of multiple data formats ), OLE provides services that make it easier for an application to call other applications for data editing. For example, the word processor supported by Ole can nest workbooks. When you want to edit a workbook, the OLE library can automatically start the workbook editor. When you exit the workbook editor, the table is updated in the original word processor document. Here, the workbook editor becomes an extension of the word processor. If you use DDE, you need to start the workbook editor explicitly. Similar to DDE technology, most Windows-based applications support OLE technology. 9 The global data in the dynamic Connection Library Win32 dynamic connection library (DLL) can be shared by all the processes that call the DLL, which opens up a new way for inter-process communication, of course, pay attention to synchronization during access. Although data can be shared between processes through DLL, we do not advocate this method from the perspective of data security. It is better to use shared memory with access control. 10 Remote Procedure Call the Remote Procedure Call (RPC) provided by Win32 API allows applications to call functions remotely, which makes process communication over the network as simple as function call. RPC can be used between different processes on a single machine or in the network. Since the RPC provided by Win32 API complies with the OSF-DCE (Open Software Foundation distributed computing environment) standard. Therefore, RPC applications written using Win32 APIs can communicate with RPC applications that support Dec on other operating systems. RPC developers can build high-performance, tightly coupled distributed applications. 11 The NetBIOS function Win32 API provides NetBIOS functions for low-level network control. This function is mainly used to compile interfaces with windows for the IBM NetBIOS system. Unless there are applications with special low-level network functional requirements, it is recommended that other applications do not use the NetBIOS function for inter-process communication. 12 sockets Windows Sockets specification is a set of network programming interfaces in Windows defined by the socket interface popular in U. C. Berkeley University bsd unix as an example. In addition to the original library functions of Berkeley socket, a group of functions for windows are also extended, allowing programmers to make full use of the Windows message mechanism for programming. Currently, more and more network applications are using sockets to implement process communication. The main reason is that sockets is more cross-platform than other IPC Mechanisms. In addition, Winsock 2.0 not only supports TCP/IP protocol, other protocols (such as IPX) are also supported ). The only drawback of sockets is that it supports underlying communication operations, which makes it inconvenient to transmit simple data between standalone processes. In this case, the wm_copydata message described below will be more suitable. 13 wm_copydata message wm_copydata is a very powerful but little-known message. When an application transmits data to another application, the sender only needs to call the sendmessage function. The parameters are the handle of the destination window, the start address of the transmitted data, and the wm_copydata message. The receiver only needs to process the wm_copy data message as it does other messages, so that the receiving and receiving sides can share data. Wm_copydata is a very simple method, which is actually implemented through file ing at the underlying layer. Its disadvantage is that it is not flexible and can only be used in a single-host Windows platform.

In Unix systems, the basic mechanisms for inter-process communication include: pipelines and named pipelines, semaphores, messages, shared memory areas, sockets

9. What is the difference between a virtual function and a common function?

1. when declaring, the virtual function should use the keyword virtual, And the definition should not be like: Virtual int func () 2. virtual functions can achieve polymorphism 3. virtual functions enable Dynamic Association and editing with high overhead

10. How to explicitly load the dynamic link library

The two methods have no difference when your program calls a dynamic library, but the steps are different during programming. Explicit calling is troublesome, but there can be no corresponding lib Library; implicit calling is easier to use, and function declaration is enough, but a lib library is required. Two methods in VC: 1. implicit call of the dynamic library: directly link to the static input library XXX in the VC project. lib, and then you can call the functions in the DLL just like calling the functions in other source files. 2. explicit call of the dynamic library: Step 1. Create a function pointer. the pointer data type must be consistent with the called DLL-derived function. 2. Call the DLL explicitly through the Win32 API function loadlibrary (). This function returns the instance handle of the DLL. 3. Use the Win32 API function getprocaddress () to obtain the function address of the DLL to be called and assign the result to the pointer type of the custom function. 4. Use the function pointer to call the DLL function. 5. After the call is completed, use the Win32 API function freelibrary () to release the DLL function.

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.