【发布时间】:2020-04-22 19:16:55
【问题描述】:
据我所知,
void 构造函数的目的是将所有元素从 choas 状态重置为正确的新生状态。
在从右值引用中窃取数据后,这个声明对我来说是非常准确的。
但直接调用 void 构造函数似乎是一种不正当用途,并且placement-new 不适用于此。
所以,
- 我应该调用 void 构造函数来重置移动语义中的对象吗?
- 我应该像这样写reset()和invoke()吗?
- void 构造函数应该做什么?
- 我的字符串实现是否足够好?
#include <cstring>
class STR_imp
{
char* cstr;
static size_t getSize(const char* incstr)
{
return std::strlen(incstr)+1;
};
STR_imp& fillBy(const char* incstr)
{
for(int i=0,size=getSize(incstr);i<size;i++)
this->cstr[i]=incstr[i];
return *this;
};
STR_imp& reset()
{
this->cstr=nullptr;
return *this;
};
STR_imp& invoke()
{
if(this->cstr!=nullptr)
delete[] this->cstr;
return *this;
};
public:
STR_imp():cstr(nullptr)
{};
~STR_imp()
{this->invoke().reset();};
STR_imp(const char* const& incstr);//splited for reading
STR_imp(char*&& incstr):cstr(incstr)
{
incstr=nullptr;
};
STR_imp(const STR_imp& instr);//splited for reading
STR_imp(STR_imp&& instr):cstr(instr.cstr)
{
instr.reset();
};
STR_imp& operator= (const char* const& incstr);//splited for reading
STR_imp& operator= (char*&& incstr)
{
this->invoke();
this->cstr=incstr;
incstr=nullptr;
return *this;
};
STR_imp& operator= (const STR_imp& instr);//splited for reading
STR_imp& operator= (STR_imp&& instr)
{
this->invoke();
this->cstr=instr.cstr;
instr.reset();
return *this;
};
char* operator() ()
{
return this->cstr;
};
};
STR_imp::STR_imp(const char* const& incstr):cstr(new char[getSize(incstr)])
{
this->fillBy(incstr);
};
STR_imp::STR_imp(const STR_imp& instr):cstr(new char[getSize(instr.cstr)])
{
this->fillBy(instr.cstr);
};
STR_imp& STR_imp::operator= (const char* const& incstr)
{
this->invoke();
this->cstr=new char[getSize(incstr)];
this->fillBy(incstr);
return *this;
};
STR_imp& STR_imp::operator= (const STR_imp& instr)
{
this->invoke();
this->cstr=new char[getSize(instr.cstr)];
this->fillBy(instr.cstr);
return *this;
};
【问题讨论】:
-
你过度设计了;不需要 3/4 的代码。目前还不清楚
invoke()做什么甚至应该做什么。 Invoke 是 call 或 use 的同义词。 -
什么是“空构造函数”?我从来没有听说过。
-
通过 const 引用和右值引用传递
char指针有什么用?一个STR_imp(const char *);就足够了。此外,除了复制/移动之外,您可能不应该向operator=添加任何重载。由于非explicit构造函数,您仍然可以将char指针分配给您的对象。 -
@AiDSl 好的。所以,是的,“默认构造函数”。
-
这是一个默认的默认构造函数。我知道。 ???愚蠢的语言。
标签: c++ constructor move-semantics