C++基本类的两种c++11写法

//基本类的两种c++11写法,之前用以前旧写法,觉得没意思太low
//1懒人写法
class T
{
public:
T() = default;
~T() = default;
T(const T&) = default;
T& operator=(const T&) = default;

//增加移动构造
T(T&&) = default;
T& operator=(T&&) = default;
unique_ptr<char>data;//智能指针
};

//2.c++标准实现法
class Tx {
public:
Tx() { data = nullptr; }
~Tx() {}
Tx(Tx& x) { data = std::move(x.data); }
Tx& operator=(Tx& x) {
(this != &x) ? data = std::move(x.data): data;
return *this;
}

//增加移动构造
Tx(Tx&&) = default;
Tx& operator=(Tx&&) = default;
unique_ptr<char>data ;//智能指针

//测试函数
Tx(const char* str) {
unique_ptr<char> p(new char[strlen(str) + 1]);
strcpy(p.get(), str);
data = std::move(p);
}
};

int main()
{
Tx x =Tx("123");
return 0;
}

posted @ 2021-07-12 22:24  默*为  阅读(305)  评论(0编辑  收藏  举报