C + + (C + + memory management, inline functions, type conversions, namespaces, string classes)

Source: Internet
Author: User

Memory Management New/delete

The malloc and free two system functions are available in the C language, #include

struct STU
{
int age;
String name;
};
stu* pstu = new stu{23, "Assassin"};
cout<

charnewint[4];strcpy(p,"china");cout<<p<<endl;intnewint[5];//int *pi = new int[5]{0};//初始化0,一般不这样memset(pi,0,sizeof(int[5]));//初始化for(int05;i++){    cout<<pi[i]<<endl;}

To generate an array of pointers:

charnewchar*[5]{NULL};p[0"assassin";p[1"automan";p[2"wunworld";while(*p){    cout<<*p++<<endl;}/*assassinautomanwunworld*/

Generate two-dimensional arrays;

int(*PA) [4] =New int[3][4]{{0}};//Initialize for(inti =0; I <sizeof(int[3][4])/sizeof(int[4]); i++) { for(intj =0; J <4; j + +) {cout<<pa[i][j]<<" "; } Cout<<endl;}/*0 0 0 00 0 0 00 0 0 0*///Multidimensionalint(*PPP) [3][4][5] =New int[2][3][4];

Release Delete:

intnewint;delete p;intnewint[100];delete []a;//正确的释放delete a;//只把第一个释放了int (*aa)[4newint[3][4];delete []aa;//多位的数组也是一个方括号,底层用递归

Precautions

1,new/delete is a keyword that is more efficient than malloc and free.
2, paired use, avoid memory leaks and multiple releases.
3, avoid, cross-use. For example, malloc application space to delete,new out of space is free;

//cint *p = (int *)malloc(100);if(NULL == p)    return-1;//c++intnewint[100];if(pi == NULL)    return-1;
inline functions (inline function)

There is a concept of macro function in C language. Macro functions are built into the calling code, avoiding the overhead of function calls. However, due to the processing of macro functions in the preprocessing stage, missing syntax detection and possible semantic errors, it is easy to make the memory text segment volume larger, not type check.

#define SQR(i) ((i)*(i))int main(){    int i=0;    while(i<5)    {        // printf("%d\n",SQR(i++));        printf("%d\n",sqr(i++));    }    return0;}int sqr(int i){    return i*i;}/*优点:一段高度抽象的逻辑,不易产生歧义,是的text段体积变小,会类型检查。缺点:函数调用的压栈与出栈的开销*/

Inline functions have the advantage of both macros and functions. The system has its own optimization scheme, and inline becomes a recommendation to the compiler.

inlineint sqr(int i){    return i*i;}

Evaluation
Pros: Avoid extra overhead when calling (stack and stack operations)
Cost: Because the function body of an inline function appears multiple "Replicas" in the code snippet, it increases the space of the code snippet.
Essence: Increase the efficiency of program running time at the expense of code segment space.
Application scenario: The function body is "small" and is called "frequently".

Forced type conversions
static_cast//对于隐时类型可以转化的reinterpret_cast//对于无隐式的类型转化,static_cast不可用const_cast//dynamic_cast//

Static_cast

float5.6;int5static_cast<int>(a);//把a转成int赋值给bvoid *p,int *q;p = q;//可以q = p;//不可以,任何指针都可以赋值给void *类型,但是void *类型不可以赋值给指针类型。static_cast<int*>(p);

Reinterpret_cast

int a[5] = {1,2,3,4,5};intreinterpret_cast<int*>((reinterpret_cast<int>(a)+1));

Const_cast
(off) constant type conversions, only reference to pointers and references
Const must not be modified

voidFuncConst int&r) {}voidFunc2 (int& V) {Cout<<v<<endl;}intMain () {Const intA = +; FuncTen);//CanFunc (A+10);//Yes, there should be a const modifier in the parameter. Func2 (const_cast<int&> (a));//Because A is a const int type    int& ra =const_cast<int&> (a); RA = $; cout<<"a ="<<a<<"Ra="<<ra<<endl; cout<<"&a ="<<&a<<"RA ="<<&ra<<endl;/*a = RA =&a = 0x ... Not the same    */}

The constant used to remove the object (Cast away the constness) uses Const_cast to remove the const-Qualifier for the purpose of modifying its contents, using Const_cast to remove the const qualifier, usually for the function to accept the actual argument.
You can change the member variables of a const custom class, but for a built-in data type, it behaves undefined behavior.

CONST constant Variable
#defined N 200 //宏,在于处理的发生了替换constint100;//编译阶段发生了替换//const 永远不会发生改变
Namespaces (namespace Scope)
//全局无名空间int55;int main(){    int *p = &v;//访问全局的    int v =5;    cout<<v<<endl;//5    cout<<*p<<endl;//55    cout<<::v<<endl;//::作用域运算符,前面要命名空间,平常调配用的函数之前省略::        return0;}

Namespace is the re-partitioning of the global namespace

#include<iostream>usingnamespace std;namespace Spac{    int a;//全局变量     struct Stu{};//数据类型     void func();//函数     namespace//其它命名空间 }

Use:

#include<iostream>usingnamespace std;namespace Space {    int x;    int y;}namespace Other {    int x;    int y;}int main(){    200;//这种与本地的不会冲突    cout<<Space::x<<endl;//200    using Space::x;//在这作用域内的x都是Space命名空间中的x    20;    cout<<x<<endl;    using Space Space;//直接把Space这个命名空间打开    20;    30;    return0;}

Conflict resolution between various

Use the minimum unit of scope block

#include<iostream>usingnamespace std;//标中库空间命名namespace Space {    int x;    int y;}namespace Other {    int x;    int y;}int main(){    {        using Space Space;        20;        30;    }    {        using Space Other;        50;        70;    }    int x,y;    return0;}

Nesting support

namespace Space {    int x;    int y;    namespace Other {        int m;        int n;    }}int main(){    usingnamespace Space::Other;//使用Other命名空间中的变量,不建议嵌套    30;    return0;}
Use in collaborative development
namespace Space {    int x;}namespace Space {    int y;}//命名空间相同会自动合并int main(){    usingnamespace Space;    10;    20;    return0;}
System String Class

String is a class rather than a keyword, which is more flexible to initialize (like Var in JS)

"assassin";//赋值"assassin1";cout<<s2.size()<<endl;//大小"wunworld";s3 += s2;//拼接if(s == s2)//比较     cout<<"s = s2"<<endl;elseif(s > s2)    cout<<"s > s2"<<endl;else    cout<<"s < s2"<<endl;char buf[1024];strcpy(buf,s.c_str());//如果和字符连用时,一定用c_str(),返回的是char *类型//交换swap(string &s2)成员函数s.swap(s2);

Find:

int find(charint0);int find(charint0);//返回下标值,没有找到返回-1,默认从 0 下标开找

eg

"assassin";int n = s.find("i",0);cout<<n<<endl;//6
Array of type string
string sArray[10] = {                        "0",                        "1",                        "22",                        "333",                        "4444",                        "55555",                        "666666",                        "7777777",                        "88888888",                        "999999999",};for(int i=0; i<10; i++){    cout<<sArray[i]<<endl;}

String arrays are efficient, and if you use a two-dimensional array to store a string array, it is easy to waste space, when the number of columns is determined by the longest string. If you use a level two pointer to apply for heap space, according to the size of the corresponding space, although the problem of memory waste, but the operation is troublesome. It is efficient and flexible to store strings in string arrays.

Tips for Learning C + +:
1, in C + + almost do not need to use a macro, with a const or enum to define explicit constants, with inline to avoid the additional cost of function calls, template to describe a family of functions or types, with namespace to avoid naming conflicts.
2. Do not declare before you need the variable, so that you can initialize it immediately.
3, do not use the malloc,new operation will do better.
4, avoid using void*, pointer arithmetic, union and coercion, in most cases, coercion is a design error indicator.
5, minimize the use of arrays and C-style strings, the standard library of string and vector can simplify the program.
6. More importantly, try to think of the program as a set of concepts of interactions represented by classes and objects, rather than a bunch of data structures and some binary binaries that can be toyed with

C + + (C + + memory management, inline functions, type conversions, namespaces, string classes)

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.