移动构造函数

2020-08-27  本文已影响0人  大啸

#include <iostream>

#include <string>

#include <sstream>

#include <vector>

#include <string.h>

#include <initializer_list>

const bool debug = true;

void Debug(std::initializer_list<std::string> list)

{

if (debug)

{

for (const auto& v : list)

{

std::cout << "[" << v << " ] - ";

}

std::cout << std::endl;

}

}

class myString

{

public:

myString() : name(nullptr), len_(0)

{

Debug({ "myString default constructor" });

};

myString(const char* str, unsigned int len) : len_(++len)

{

name = new char[len];

memcpy(name, str, len);

Debug({ "myString constructor" });

}

myString(const myString& str)

{

name = new char(str.len_);

memcpy(name, str.name, str.len_);

len_ = str.len_;

Debug({ "myString copy" });

}

myString(const myString&& str) noexcept : len_(str.len_)

{

name = new char(str.len_);

memcpy(name, str.name, str.len_);

Debug({ "myString r copy" });

}

myString& operator= (const myString& str)

{

name = new char(str.len_);

memcpy(name, str.name, str.len_);

len_ = str.len_;

Debug({ "myString = " });

return *this;

}

    void set()

    {

        memset(name, 0, len_);

        const char* str = "world";

        memcpy(name, str, 7);

    }

~myString()

{

Debug({ "myString Destructor", name });

if (name != nullptr)

delete[] name;

else

std::cout << "errpor double free" << std::endl;

}

char* name;

unsigned int len_;

};

class HeadInfo

{

public:

HeadInfo(const std::string name, const std::string info)

: itsName(name), itsInfo(info) , context("hello", 6)

{

Debug({ "HeadInfo default Constructor" });

}

HeadInfo(std::string name, std::string info, myString& con)

: itsName(std::move(name)), itsInfo(std::move(info)) , context(std::move(con))

{

Debug({ "HeadInfo Constructor" });

}

HeadInfo(const HeadInfo& headinfo)

{

itsName = headinfo.itsName;

itsInfo = headinfo.itsInfo;

context = headinfo.context;

Debug({ "HeadInfo copy" });

}

HeadInfo(const HeadInfo&& headinfo) noexcept

{

itsName = headinfo.itsName;

itsInfo = headinfo.itsInfo;

context = headinfo.context;

Debug({ "HeadInfo r copy" });

}

HeadInfo& operator=(const HeadInfo& headinfo)

{

itsName = headinfo.itsName;

itsInfo = headinfo.itsInfo;

Debug({ "HeadInfo operator= " });

return *this;

}

~HeadInfo() { Debug({ "HeadInfo Destructor " }); }

std::string itsName;

std::string itsInfo;

myString    context;

};

int main()

{

std::vector<HeadInfo> vec;

vec.reserve(0);

myString str("hello", 6);

HeadInfo info("1", "2", str);

    str.set();

    std::cout << "-------------" << std::endl;

    myString&& str1 = std::move(str);

return 0;

}

上一篇下一篇

猜你喜欢

热点阅读