zoukankan      html  css  js  c++  java
  • 复习类的几个基本函数

     考个研真的把很多东西都忘光了,,,

    #include <string_view>
    #include <iostream>
    #include <string>
    #include <algorithm>
    #include <vector>
    
    using namespace std;
    
    class SampleClass
    {
    public:
        SampleClass()
        {
            cout << "constructor called" << endl;
            resource = (int *)std::malloc(sizeof(int) * 100000);
        }
        SampleClass(const SampleClass &rhs)
        {
            cout << "copy constructor called" << endl;
            resource = (int *)std::malloc(sizeof(int) * 100000); //memcpy
        }
    
        void swap(SampleClass &lhs, SampleClass &rhs) noexcept
        {
            using std::swap;
            swap(lhs.resource, rhs.resource);
        }
    
        SampleClass(SampleClass &&rhs)
        {
            cout << "move contrustor called" << endl;
            this->resource = rhs.resource;
            rhs.resource = nullptr;
        }
    
        SampleClass &operator=(SampleClass rhs)
        {
            cout << "operator = called" << endl;
            if (this == &rhs)
                return *this;
            swap(*this, rhs);
            return *this;
        }
    
        ~SampleClass()
        {
            cout << "destroyer called" << endl;
            if (resource != nullptr)
            {
                std::free(resource);
            }
        }
    
    private:
        int *resource;
    };
    
    int main(int argc, char **argv)
    {
        vector<SampleClass> vec;
        cout << "first push"
             << "capacity: " << vec.capacity() << endl;
        vec.push_back(SampleClass()); //将这个临时对象以右值构造vec中的对象
        cout << "second push"
             << "capacity: " << vec.capacity() << endl;
        vec.push_back(SampleClass());
        cout << "emplace_back"
             << "capacity: " << vec.capacity() << endl;
        vec.emplace_back();
        cout << "resize"
             << "capacity: " << vec.capacity() << endl;
        vec.resize(3);
    
        SampleClass a;
        SampleClass b;
        cout << "assignment" << endl;
        a = b;
        cout << "leave main" << endl;
        return 0;
    }

    Mingw的输出:

  • 相关阅读:
    软件性能测试知识汇总
    软件功能测试知识汇总
    机器学习——KNN算法(k近邻算法)
    Shell脚本语法
    机器学习环境搭建及基础
    shell基础及变量
    查准率和召回率理解
    python中的矩阵、多维数组
    链表:反转链表
    栈和队列:生成窗口最大值数组
  • 原文地址:https://www.cnblogs.com/manch1n/p/14691606.html
Copyright © 2011-2022 走看看