• c++编程之内存模型


    我们在编程的时候,无可避免要申明变量,在这个变量可以是在()中,可以在{}中,也可以直接在外面,也可以用new的方式.那么当我们在申明变量的时候,实质上我们所做的工作是:关联了一个内存模型

    上代码:

     1 #include <iostream>
     2 #include <thread>
     3 #include <chrono>
     4 #include <mutex>
     5 # include<string>
     6 using namespace std;
     7 mutex mtx;
     8 void fn1()
     9 {
    10     for (int i = 0; i < 5; i++)
    11     {
    12         unique_lock<mutex> lock(mtx);
    13         cout << "线程" << this_thread::get_id() << ":" << "The thread1 is running !" << endl;
    14     }
    15 }
    16 
    17 void fn2()
    18 {
    19     for (int i = 0; i < 5; i++)
    20     {
    21         unique_lock<mutex> lock(mtx);
    22         cout << "线程" << this_thread::get_id() << ":" << "The thread2 is running !" << endl;
    23     }
    24 }
    25 
    26 
    27 class fun{
    28 private:
    29     string name;
    30     int age;
    31 public:
    32     fun(){};
    33     fun(string name, int age)
    34     {
    35         this->name = name;
    36         this->age = age;
    37     }
    38     void ShowName()
    39     {
    40         cout << name << endl;
    41     }
    42     ~fun(){};
    43 };
    44 
    45 int main()
    46 {
    47     thread t1(fn1);
    48     thread t2(fn2);
    49     t1.detach();
    50     t2.detach();
    51 
    52     this_thread::sleep_for(chrono::milliseconds(1000));
    53     fun zhangsan("zhangsan", 5);
    54     fun*lisi = new fun("zhangsan", 5);//动态申请的方式,但是要用到指针
    55     zhangsan.ShowName();
    56     lisi->ShowName();
    57     delete lisi;
    58     //lisi->ShowName();
    59     lisi = nullptr;
    60     getchar();
    61     return 0;
    62 }

    我们分析上面程序中的三个典型变量:zhangsan,lisi(在main函数中的),以及第七行的mtx。

    zhangsan是一个局部变量,存在于栈空间,lisi也是一个局部变量,但是其采用new的方式,则lisi 属于动态内存分配,存在于堆区,而mtx属于全局变量,存在于某一个静态区。

    c++中的典型内存模型为:C++的内存模型 = 静态存储区(全局变量,静态变量)+堆(malloc,new的对象)+栈。

    对于上述一段代码,还应该关注的是:如何使用 new ;new 必须和指针变量相关联!!!   用法是:类型 指针 = new 类型

  • 相关阅读:
    Findbugs初探-使用idea获取findbugs插件
    idea 14运行java工程报错-Dmaven.multiModuleProjectDirectory system propery is not set. Check $M2_HOME environment variable and mvn script match.
    Linux定时任务
    模块和包
    流程控制&&函数
    Python 变量与数据类型
    使用代码上传文件示例
    好用的代码示例
    JedisCluster API 整理
    springboot实现转发和重定向
  • 原文地址:https://www.cnblogs.com/shaonianpi/p/11439585.html
Copyright © 2020-2023  润新知