您现在的位置是:首页 >技术交流 >MyString 类 构造函数 对象行为 设计模式 单例模式网站首页技术交流
MyString 类 构造函数 对象行为 设计模式 单例模式
                简介MyString 类 构造函数 对象行为 设计模式 单例模式            
            系列文章目录
文章目录
前言
记录不同行为的拷贝与构造情况。
一、MyString类
错误的
class MyString
{
private:
    char* chs;
public:
    MyString():chs(nullptr)
    {
        std::cout << "默认构造 MyString(),thread_id: " 
                  << std::this_thread::get_id() << std::endl;
    }
    MyString(const char* s)
    {
        chs = new char[strlen(s)+1];
        memcpy(chs, s, strlen(s)+1);
        std::cout << "重载构造 MyString(const char* s),thread_id: " 
                  << std::this_thread::get_id() << std::endl;
    }
    virtual ~MyString()
    {
        if(chs) {
            delete[] chs;
            chs = nullptr;
        }
        std::cout << "析构 ~MyString(),thread_id: " 
                  << std::this_thread::get_id() << std::endl;
    }
    MyString(const MyString& str)
    {
        if(chs){
            delete[] chs;
        }
        chs = new char[strlen(str.chs)+1];
        memcpy(chs, str.chs, strlen(str.chs)+1);
        std::cout << "拷贝构造 MyString(const MyString&),thread_id: " 
                  << std::this_thread::get_id() << std::endl;
    }
    MyString& operator=(const MyString& str)
    {
        if (&str == this)
            return *this;
        if(chs){
            delete[] chs;
        }
        chs = new char[strlen(str.chs)+1];
        memcpy(chs, str.chs, strlen(str.chs)+1);
        std::cout << "赋值 operator=,thread_id: " 
                  << std::this_thread::get_id() << std::endl;
    }
    void operator()()
    {
        std::cout << "函数对象 operator()(),thread_id: " 
                  << std::this_thread::get_id() << std::endl;
    }
    void memberfn()
    {
        std::cout << "成员函数 memberfn,thread_id: " 
                  << std::this_thread::get_id() << std::endl;
    }
};
 
正确的
#include <iostream>
#include <new>
#include <memory>
#include <thread>
#include <string.h>
class MyString
{
public:
    char* chs;
public:
    MyString()
    {
        chs = new char[1];
        *chs = '