• 复习类的几个基本函数


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

    #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的输出:

  • 相关阅读:
    数据库与ORM
    Django之Template
    Django路由配置系统、视图函数
    Django基本命令
    MVC和MTV模式
    转载:CSS实现三栏布局的四种方法示例
    转载:JSONObject.fromObject(map)(JSON与JAVA数据的转换)
    转载:CURL常用命令
    转载:详解CSS选择器、优先级与匹配原
    转载:Struts2.3.15.1升级总结
  • 原文地址:https://www.cnblogs.com/manch1n/p/14691606.html
Copyright © 2020-2023  润新知