C++ (4) C++ のメモリ管理と名前空間

メモリ管理

新規/削除

C言語のmalloc freeでヒープメモリの適用と解放が完了します。

C++ の新しい削除クラス

new: ストレージスペースを動的に申請するための演算子。戻り値はアプリケーションスペースの対応するデータ型のアドレスです。

int *p = new int(10); 初期値 10 の整数データを適用します。

int *p = new int[10]; 10 個の整数データ要素を格納できる配列を適用し、その最初のアドレスは arr です

一変量空間

#include <iostream>
#include <stdlib.h>
using namespace std;

//malloc free  # include <stdlib.h>  库函数
//new delete key work 关键字

int main()
{
    //C
    int *p = (int*)malloc(sizeof(int));
    int *p = static_cast<int*>(malloc(sizeof(int)));

    //C++  单变量空间
    int *p = new int(200);
    //*p = 200;
    cout<<*p<<endl;

    string *ps = new string("aaa");
    //*ps = "china";
    cout<<*ps<<endl;

    struct Stu{
        int age;
        string name;
    };
    Stu *pStu = new Stu{10, "bob"};
    cout<<pStu->age<<endl;
    cout<<pStu->name<<endl;

    return 0;
}

多変量空間配列

#include <iostream>
#include <string.h>  // #include <cstring>
#include <stdlib.h>
using namespace std;

int main()
{
	char* p = new char[4];
	const char* source = "aa";
	strcpy_s(p, 4, source);
	cout << "p: " << p << endl;

    int *pi = new int[5]{0};
    memset(pi, 0, sizeof(int[5]));
    for(int i = 0; i < 5; i++)
    {
        cout<<pi[i]<<endl;
    }

    char **ppc = new char*[5]{NULL};
    ppc[0] = new char[10];
    strcpy(ppc[0], "china");
    ppc[1] = "automan";
    ppc[2] = "greatwall";

    while(*ppc)
    {
        cout<<*ppc++<<endl;
    }

    return 0;
}

一次元、多次元

#include <iostream>
#include <stdlib.h>
#include <string.h>
using namespace std;

int main()
{
    int(*pa)[4] = new int[3][4]{ {0} };
	for (int i = 0; i < sizeof(int[3][4]) / sizeof(int[4]); i++)
	{
		for (int j = 0; j < 4; j++)
		{
			cout << pa[i][j] << "";
		}
		cout << endl;
	}

    int (*px)[3][4][5] = new int[2][3][4][5];
    
    return 0;
}

 メモリ解放

#include <iostream>
#include <stdlib.h>
#include <string.h>
using namespace std;

int main()
{
    int *p = new int;
    delete p;

    int *q = new int[1000];
    delete []q;

    //多维只用一个框即可,内核用递归删除
    int *r = new int[1000][][];
    delete []r;

    return 0;
}

インライン関数

インライン関数 インライン関数

マクロ関数と通常関数の間

マクロ機能

利点: コードをインラインで記述し、関数呼び出しを回避します。

短所: 曖昧さが生じやすく、テキストセグメントのサイズが大きくなりやすい。

通常の関数

利点: 高度に抽象化されたロジックは曖昧さを引き起こしにくく、テキストセグメントの量が削減されます。

欠点: 関数呼び出しのプッシュとポップのオーバーヘッド。

インラインインライン関数

利点: 高度に抽象化されたロジックはあいまいさを引き起こしにくく、テキスト セグメントのサイズが小さくなり、型チェックを実行してスタックのプッシュとポップのオーバーヘッドを回避します。

コスト: コードセグメントスペースの増加

本質: コードセグメントのスペースを犠牲にして、プログラムの実行時間の効率を向上させる

適用可能: コード本体が小さく、頻繁に呼び出される

なぜすべての関数をインライン化しないのでしょうか?

インラインが多すぎると、インラインがコンパイラへの提案になります

関数の行数が 10 行以下の場合にのみ、関数をインラインとして定義します。

#include <iostream>
using namespace std;

#define SQR(i) ((i)*(i))  //宏函数

int sqr(i)  //普通函数
{
    return i * i;
}

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


int main()
{
    int i = 0;
    while(i < 5)
    {
        cout<<SQR(i++)<<endl;
    }

    return 0;
}

キャスト

#include <iostream>
#include <stdlib.h>

using namespace std;

void func(int & v)
{
    cout<<v<<endl;
}

int main()
{
    static_cast  对于隐式类型可以转化的,即可用此类型

    float a = 5.6;
    int b = 5;

    //隐式类型转换
    a = b;
    b = a;

    b = static_cast<int>(a);
    a = static_cast<float>(b);

    void *p; int *q;
    p = q;
    q = p;  //报错
    q = static_cast<int*>(p);

    int x = 10;
    int y = 3;
    float z = static_cast<float>(x) / y;

    char * pc = static_cast<char*>(malloc(100));

    reinterpret_cast  对于无隐式的类型转化,static_cast不可用

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

    int *p = (int*)((int)a+1);
    int *p = reinterpret_cast<int*>((reinterpret_cast<int>(a) + 1));
    cout<<hex<<*p<<endl;

    const_cast  脱常,只能应用于指针和引用
    const 修饰的一定不可以改

    const int a = 19;
    func(const_cast<int&>(a));

    dynamic_cast

    return 0;
}

マクロ、前処理フェーズ中に置き換えられます

定数コンパイルフェーズ中に置換が発生しました

絶え間ない

名前空間

名前空間は大規模プロジェクト用に開発され、名前の競合を回避するメカニズムです。

:: スコープ演算子、名前空間が前に付く

グローバルな名前のない名前空間

部分的

名前空間は、グローバル名前空間の下位部分です。

#include <iostream>

using namespace std;

int v = 55;  // 全局

int main()
{
    int b = 10;  // 局部
    int *p = &v;
    cout<<v<<endl;
    cout<<b<<endl;

    cout<<::<<endl;

    return 0;
}

#include <iostream>

using namespace std;

namespace Space{
    int x;
    void func()
    {
        printf("void func");
    }
    struct Stu
    {
        int a;
        int b;
    }
}

namespace Other{
    int x;
    int y;
}

int main()
{
    Space::x = 200;
    cout<<Space::x<<endl;

    using Space::x;
    x = 20;
    cout<<x<<endl;

	using namespace Space;
	Stu s = {1, 2};
	cout << s.a << "---" << endl;

    using namespace Other;
    Other::x = 10;
    y = 20;
    cout<<Other::x<<y<<endl;

    int m, n;
    std::cin>>m>>n;
    std::cout<<m<<n<<std::endl;

    return 0;
}

同じ名前のローカル変数がある場合、競合が発生します。

ネスティングをサポート

#include <iostream>

using namespace std;

namespace Space{
    int a;
    int b;

    namespace Other{
        int m;
        int n;
    }
}

int main()
{
    using namespace Space::Other;
    m = 20;

    return 0;
}

共同開発

#include <iostream>

using namespace std;

namespace Space
{
    int x;
}

namespace Space
{
    int y;
}

int main()
{
    using namespace Space;
    int x = 10;
    int y = 20;

    cout<<x<<y<<endl;

    return 0;
}

同じスペース名は結合されます

文字列クラス

#include <iostream>

using namespace std;

//string 不是关键字,而是一个类

int main()
{
    std::string str;

    string str("china");
    string str = "china";
    str = "good";
    string str2(str);

    cout<<str<<endl;
    cout<<str2<<endl;

    string s = "china";
    s[3] = 'w';
    cout<<s<<endl;

    char buf[1024];
    strcpy(buf, s.c_str());  //string -> char* c_str返回字符串
    cout<<buf<<endl;

    str.swap(str2);  //交换两个字符串  swap 成员函数

    int n = str.find('i', 0); //查找一个字符的位置,返回下标,找不到返回-1
    cout<<"n = "<<n<<endl;

    string sArray[10] = {
        "0",
        "1",
        "22",
        "333",
        "4444",
        "55555",
        "666666",
        "7777777",
        "88888888",
        "999999999",
    };

    for(int i = 0; i < 10; i++)
    {
        cout<<sArray[i]<<endl;
    }

    return 0;
}

要約する

malloc free C ライブラリ関数; new delete new[] delete[] キーワード

新規削除 > malloc free

一変量空間を適用する

配列の申請 1次元 多次元

#include <iostream>

using namespace std;

struct Str
{
    char *p;
};

int main()
{
    string *ps = new string;
    *ps = "china";

    cout<<ps<<endl;   //输出地址  对象的地址
    cout<<*ps<<endl;  //输出值    对象的内容
    
    struct Str str = {"abcdefg"};

    int *pi = new int[10]{0};

    char **ppc = new int*[5]{NULL};  //定义指针数组

    int (*p)[4] = new int[3][4];

    return 0;
}

消去(0, npos)

0から開始して「 」の位置まで削除

str.erase(0, str.find_first_not_of(' '));

購読後、後で削除する

str.erase(str.find_last_not_of(' ') + 1);

#include <iostream>
#include <string.h>
#include <stdlib.h>

using namespace std;

int main()
{
    FILE *fp = fopen("aa.txt", "r+");  //打开并读取文件
    if(fp == NULL)
        return -1;

    vector<string> vs;
    char buf[1024];
    
    while(fgets(buf, 1024, fp) != NULL)  //读取文件内容
    {
        vs.push_back(buf);  // 内容接在后边
    }

    for(int i = 0; i < vs.size(); i++)
    {
        cout<<vs[i]<<endl;
    }
    fclose(fp);
    
    return 0;    
}

おすすめ

転載: blog.csdn.net/jiangyangll/article/details/132289196