zoukankan      html  css  js  c++  java
  • 70、对象复用的了解,零拷贝的了解

    对象复用

    对象复用其本质是一种设计模式:Flyweight享元模式。

    通过将对象存储到“对象池”中实现对象的重复利用,这样可以避免多次创建重复对象的开销,节约系统 资源。

    零拷贝

    零拷贝就是一种避免 CPU 将数据从一块存储拷贝到另外一块存储的技术。

    零拷贝技术可以减少数据拷贝和共享总线操作的次数。

    在C++中,vector的一个成员函数emplace_back()很好地体现了零拷贝技术,它跟push_back()函数一 样可以将一个元素插入容器尾部,区别在于:使用push_back()函数需要调用拷贝构造函数和转移构造 函数,而使用emplace_back()插入的元素原地构造,不需要触发拷贝构造和转移构造,效率更高。举 个例子:

    #include <vector>
    #include <string>
    #include <iostream>
    using namespace std;
    struct Person
    {
    string name;
    int age;
    //初始构造函数
    Person(string p_name, int p_age): name(std::move(p_name)), age(p_age)
    {
    cout << "I have been constructed" <<endl;
    }
    //拷贝构造函数
    Person(const Person& other): name(std::move(other.name)),
    age(other.age)
    {
    cout << "I have been copy constructed" <<endl;
    }
    //转移构造函数
    Person(Person&& other): name(std::move(other.name)), age(other.age)
    {
    cout << "I have been moved"<<endl;
    }
    };
    int main()
    {
    vector<Person> e;
    cout << "emplace_back:" <<endl;
    e.emplace_back("Jane", 23); //不用构造类对象
    vector<Person> p;
    cout << "push_back:"<<endl;
    p.push_back(Person("Mike",36));
    return 0;
    }
    //输出结果:
    //emplace_back:
    //I have been constructed
    //push_back:
    //I have been constructed
    //I am being moved.
  • 相关阅读:
    PTA(Advanced Level)1037.Magic Coupon
    PTA(Advanced Level)1033.To Fill or Not to Fill
    PTA(Basic Level)1020.月饼
    PTA(Advanced Level)1048.Find Coins
    PTA(Advanced Level)1050.String Subtraction
    PTA(Advanced Level)1041.Be Unique
    PTA(Basci Level)1043.输出PATest
    PTA(Basic Level)1039.到底买不买
    PTA(Basic Level)1033.旧键盘打字
    PTA(Advanced Level)1083.List Grades
  • 原文地址:https://www.cnblogs.com/crbhf/p/15087858.html
Copyright © 2011-2022 走看看