C ++

Source: Internet
Author: User
Document directory
  • 1. New is re-allocated on the existing Stack
  • 2. Some operators that like errors (parentheses, user-defined)
  • 3. Const Modifier
  • 4. Use const_cast for conversion
  • 5. objects that cannot be copied
  • 6. rtti (run-time type identification)
  • 7. typeid
  • 8. Reload arrows
  • 9. Waiting .....
1. New is re-allocated on the existing Stack

Char * CP = new char [2, 100], CH [50];
Int * P = new (CP) int;
* P = 58;
Delete P;
CP = CP + sizeof (INT );
Delete CP; // error, cannot be released twice

Int * P = new (CH) int; // use the existing stack space to re-allocate

Delete * P; // error. Stack space cannot be released

2. Some operators that like errors (parentheses, user-defined)

# Include <iostream> using namespace STD; Class test {friend ostream & operator <(const ostream & O, const Test & T );}; ostream & operator <(ostream & O, const Test & T) {cout <"test" <Endl; return O;} class time {public: int operator () () {// note the differences between the highlighted version 0 and the following custom conversion cout <"Bracket" <Endl; return H * 3600 + M * 60 + S ;} operator test () {// custom conversion 1. user-Defined conversions cannot specify the return type 2. "Time: Operator test": A cout <"cast test" <Endl; static test T; // return T; // return a reference of class test} void operator () (int h, int M, int s) {// reload Version 3 this-> H = h; this-> M = m; this-> S = s;} PRIVATE: int h; int m; int s ;}; int main (INT argc, char ** argv) {time t; t (, 1); // braces are reloaded with three parameters cout <t () <Endl; // The version 0 cout is overloaded with parentheses <Test (t); Return 0 ;}

1. User-Defined conversions cannot specify the return type 2. "Time: Operator test": A value must be returned.

3. Const Modifier

Const char * const Foo (char const * const Str) const
The first const indicates that the return type is const, that is, the return value of this function cannot be used as the left value.
The second const indicates that the pointer is non-mutable, but this can be omitted because the return type is already Const.
The third cosnt represents the constant of STR, so its content cannot be changed. It can be written before the char.
The fourth cosnt indicates the constant of the STR pointer, that is, the pointer cannot point to another address.
The fifth cosnt indicates the constant of the function (provided that it is a member function of the class) and cannot modify the data member of the class.

For more detailed usage, refer to: http://blog.csdn.net/Eric_Jo/article/details/4138548

4. Use const_cast for conversion

Usage: const_cast <type_id> (expression)
This operator is used to modify the const or volatile attributes of the type. In addition to const or volatile modification, type_id and expression are of the same type.
· Constant pointers are converted to non-constant pointers and still point to the original object;
· Constant reference is converted to a non-constant reference and still points to the original object;
· Constant objects are converted to non-constant objects.

The following code is used to describe the problem.

Code 1:

const int m = 15;const int *const_p = &m;int *p = const_cast<int*> (const_p) ;*p = 18;cout << *p<<*const_p<<m; ;

Output result: 181815

Code 2:

int m = 15;const int *const_p = &m;int *p = const_cast<int*> (const_p) ;*p = 18;cout << *p<<*const_p<<m; ;

Output result: 181818

Code 3:

Const int M = 15; const Int & mconst = m; Int & MNC = const_cast <Int &> (mconst ); // or Int & MNC = const_cast <Int &> (m); MNC = 80; cout <MNC <mconst <m;

Output result: 808015

This is a strange thing, but it is a good thing: const in C ++ is const, which is the constant change in the outside world. Otherwise, it would be messy, and the const would have no significance.

The ibm c ++ Guide calls "* Modifier
= 7; "is" undefined behavior )". The so-called undefined statement does not have clear provisions in the Standard C ++, And the compiler determines how to handle the statement.
The Left shift operation of bitwise operations can also be considered an undefined action, because we are not sure whether it is logical left shift or arithmetic left shift.
For example, the following statement: V [I] = I ++; is also an undefined behavior, because we do not know whether to perform auto-increment first or to find the position in the array first.
What we can do for undefined behaviors is to avoid such statements. For const data, we must make sure that the value of const data is not re-assigned.

More detailed content reference: http://www.cnblogs.com/ider/archive/2011/07/22/cpp_cast_operator_part2.html

5. objects that cannot be copied

Objects that cannot be copied in C ++ are generally I/O objects. The reason is that I/O objects operate on the handles of various input/output devices. If copying is allowed, two different objects may operate on the same device handle. If one of the devices is destructed, the device is disabled, but the other object still uses the handle, leading to unpredictable runtime errors, it is dangerous. Therefore, IO objects cannot be copied.

Non-replicable implementation:

In C ++, copying a class mainly involves copying constructor and value assignment function. In addition, it is a member method specially implemented for copying. Because the copy constructor and assignment function are automatically generated by the C ++ compiler and are public members when the user provides them, therefore, the default C ++ class has the copy function.ThereforeThe constructor and the value assignment function are set as private members,

Leave a question here: friends and friends can access private friends. What if they do not allow friends and friends to access some private friends ???

6. rtti (run-time type identification)

Let's take a look at the following code:

# Include <iostream> using namespace STD; Class A {int M [15]; public: Virtual void prina () {cout <"this is a" <Endl ;}}; Class B: Public A {// what will happen if it is replaced by virtual inheritance? Public: Virtual void prinb () {cout <"This is B" <Endl ;}}; void fun_1 (A * pA) {B * pb = dynamic_cast <B *> (PA); If (PB = NULL) {pa-> prina ();} else {Pb-> prinb () ;}} void fun_2 (A * pA) {B * pb = NULL; If (typeid (* pA) = typeid (B )) {Pb = static_cast <B *> (PA); Pb-> prinb ();} else {pa-> prina () ;}} int main () {// cout <sizeof (a) <sizeof (B); // 6464a * pA = new B; cout <typeid (PA ). name () <Endl; cout <typeid (* pA ). name () <Endl; fun_1 (PA); fun_2 (PA); A * PAA = new A; fun_1 (PAA); fun_2 (PAA); Return 0 ;}

You don't need to check the running result first. You can try to check whether it is the same as the running result!

Running result:

Class *
Class B
This is B
This is B
This is
This is
Press any key to continue...

As for the sub-statement, I will not get it out here. Please give a reference link!

More details reference: http://www.cnblogs.com/zhyg6516/archive/2011/03/07/1971898.html

7. typeid

Before you unveil the mystery of typeid, let's take a look at it.Rtti(Run-time
Type identification, runtime type recognition), which enables the program to obtain the actual derived type of the object pointed to by the base pointer or reference, that is, the program that allows the operation of objects by pointer or reference to the base class can obtain the actual derived type of the pointer or reference to the objects. In C ++, two operators are provided to support rtti: dynamic_cast and typeid.
Dynamic_cast allows type conversion at runtime, so that the program can safely convert the type in a class hierarchy. Correspondingly, there is a non-secure conversion operator static_cast, this is not the focus of this article, so we will not detail it here. If you are interested, you can check the information on your own. Let's start today's topic: typeid.

TypeidIs one of the keywords of C ++, equivalent to operators like sizeof. The return result of the typeid operator is namedType_infoStandard library type constant object reference (defined in the header file typeinfo, let's take a look at the source code in the Vs and GCC libraries later), its expression has two forms.


If the expression type is a class type and contains at least one virtual function, the typeid operator returns the dynamic type of the expression, which must be calculated at runtime. Otherwise, the typeid operator returns the static type of the expression, it can be computed during compilation.
The iso c ++ standard does not have the exact definition of type_info, which defines compiler-related, however, the standard specifies that the implementation must provide the following four operations (in the subsequent sections, I will analyze the source code of the type_info class file ):

T1 = t2 If the T1 and T2 objects are of the same type, true is returned; otherwise, false is returned.
T1! = T2 If the T1 and T2 types of the two objects are different, true is returned; otherwise, false is returned.
T. Name () Returns the C-style string of the type. The type name is generated using a system-related method.
T1.before (T2) Returns the bool value indicating whether T1 exists before T2.

The type_info class provides public virtual destructor so that users can use it as the base class. Its default constructor, copy constructor, and value assignment operator are both defined as private. Therefore, objects of the type_info type cannot be defined or copied. The only way to create a type_info object in the program is to use the typeid operator (it can be seen that if typeid is treated as a function, it should be of type_info
Youyuan ). The name member function of type_info returns the C-style string to indicate the corresponding type name, however, it is important to note that the returned type name is not necessarily consistent with the corresponding type name used in the Program (this is often the case, see the program below), which is determined by the implementation of the compiler, the standard only requires that a unique string be returned for each type.

8. Reload arrows

1. the overload arrow operator must return a pointer to the class type. 2. or return a class object that defines its own arrow operator.

# Include <iostream> using namespace STD; Class A {public: void action () {cout <"action in Class! "<Endl ;}}; Class B {A; public: A * operator-> () {return & A;} void action () {cout <"action in Class B! "<Endl;} void printb () {cout <" I am B "<Endl ;}}; class c {B; public: B operator-> () {return B;} void action () {cout <"action in Class C! "<Endl ;}; int main (INT argc, char * argv []) {B; // B-> printb (); // error c2039: "printb": B-> action (); // correct, call a: Action () C * Pc = new C; PC-> action (); // correct. Call C: Action (); C-> action (); // correct. Call C :: operator->, call B: Operator->, call a: Operator->, and call a: Action () getchar (); Return 0 ;}

9. Waiting .....

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.