码迷,mamicode.com
首页 > 其他好文 > 详细

复习类的几个基本函数

时间:2021-04-23 12:18:50      阅读:0      评论:0      收藏:0      [点我收藏+]

标签:sizeof   size   ptr   turn   com   mingw   second   private   cond   

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

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

技术图片

 

复习类的几个基本函数

标签:sizeof   size   ptr   turn   com   mingw   second   private   cond   

原文地址:https://www.cnblogs.com/manch1n/p/14691606.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!