尝试编写可以从std :: string移动语义的字符串类

Edd*_*223 3 c++ stdstring dynamic-memory-allocation move-semantics c++11

我正在编写自己的字符串类,仅仅是为了学习和巩固一些知识.我有一切工作,除了我想有一个使用移动语义与std :: string的构造函数.

在我的构造函数中,我需要复制并清空std :: string数据指针和其他东西,它需要保留为空但有效的状态,而不删除字符串指向的数据,我该怎么做?

到目前为止,我有这个

class String
{
private:
char* mpData;
unsigned int mLength;
public:
String( std::string&& str)
    :mpData(nullptr), mLength(0)
    {
    // need to copy the memory pointer from std::string to this->mpData

    // need to null out the std::string memory pointer
    //str.clear();  // can't use clear because it deletes the memory
    }
~String()
{
delete[] mpData;
mLength = 0;
}
Run Code Online (Sandbox Code Playgroud)

Jam*_*lis 7

没有办法做到这一点.实现std::string是实现定义的.每个实现都是不同的.

此外,无法保证字符串将包含在动态分配的数组中.一些std::string实现执行小的字符串优化,其中小字符串存储在std::string对象本身内.

  • `vector <string>`只需要能够从另一个`string`移动构造或移动 - 分配`string`.`string`类通过其移动构造函数和移动赋值运算符来处理它.交叉类型移动有点奇怪,但是如果你控制源类型和目标类型的实现,或者源类型提供了一些从它移动的方法(例如`unique_ptr`提供了`release`成员函数),它肯定是可能的. . (5认同)
  • @Potatoswatter:现在你不能再从仲裁字符串中移出了. (2认同)

归档时间:

查看次数:

609 次

最近记录:

13 年,8 月 前