回复 3楼 nifilmjon
我写了半个小时,才把 构造 和 赋值 写完,我没时间做这事了,
你自己写吧,不会的地方对照着 std::string 看
程序代码:
#include <cstddef>
class foo
{
public:
constexpr foo() noexcept;
constexpr foo( const char* s );
constexpr foo( const foo& other );
constexpr foo( foo&& other ) noexcept;
constexpr foo( std::nullptr_t ) = delete;
~foo();
constexpr foo& operator=( const char* s );
constexpr foo& operator=( const foo& other );
constexpr foo& operator=( foo&& other ) noexcept;
constexpr foo& operator=( std::nullptr_t ) = delete;
constexpr foo& assign( const char* s );
constexpr foo& assign( const char* s, size_t count );
constexpr void clear() noexcept;
protected:
char* p_;
size_t size_;
};
#include <iostream>
#include <cstring>
using namespace std;
constexpr foo::foo() noexcept : p_(), size_()
{
}
constexpr foo::foo( const char* s ) : foo()
{
assign( s );
}
constexpr foo::foo( const foo& other ) : foo()
{
assign( other.p_, other.size_ );
}
constexpr foo::foo( foo&& other ) noexcept : p_(other.p_), size_(other.size_)
{
other.p_ = nullptr;
other.size_ = 0;
}
foo::~foo()
{
delete[] p_;
}
constexpr foo& foo::operator=( const char* s )
{
assign( s );
return *this;
}
constexpr foo& foo::operator=( const foo& other )
{
if( this != &other )
assign( other.p_, other.size_ );
return *this;
}
constexpr foo& foo::operator=( foo&& other ) noexcept
{
p_ = other.p_;
size_ = other.size_;
other.p_ = nullptr;
other.size_ = 0;
return *this;
}
constexpr foo& foo::assign( const char* s )
{
clear();
return assign( s, s?strlen(s):0 );
}
constexpr foo& foo::assign( const char* s, size_t count )
{
clear();
if( s && count )
{
size_ = count;
p_ = new char[size_+1];
memcpy( p_, s, size_ );
p_[size_] = '\0';
}
return *this;
}
constexpr void foo::clear() noexcept
{
if( p_ )
{
size_ = 0;
delete[] p_;
p_ = nullptr;
}
}