为动态字符串数组创建一个不带=赋值的Copy函数

C++ - Creating a Copy function without = assignment for a Dynamic String Array

本文关键字:赋值 函数 Copy 一个 数组 字符串 动态 创建      更新时间:2023-10-16

试图为动态分配的数组编写复制函数。

在我的头文件中我有:

#include <memory>
#include <string>

using std::string;
using std::unique_ptr;
using std::make_unique;
class StringSet{
public:
    //create an empty set
    StringSet() = default;
    StringSet(int capacity);
    //copy a set
    StringSet(const StringSet&);
    StringSet& operator[](const int);
    //Insert a string to the set
    bool insert(string);
    //Remove a string from the set
    bool remove(string);
    //Test whether a string is in the set
    int find(string) const;
    //Get the size of the set
    int size() const;
    //get string at position i
    string get(int i) const;
    //Return the set union of the set and another StringSet
    StringSet setunion(const StringSet&) const;
    //Return the intersection of the set and another StringSet
    StringSet intersection(const StringSet&) const;
    //Return the set diffference of the set and another StringSet
    StringSet difference(const StringSet&) const;
    //prevent default copy assignment
    StringSet& operator=(const StringSet&) = delete;
    int NOT_FOUND = -1;
    static constexpr int def_capacity {4};
private:
    int arrSize {def_capacity};
    int currentSize {0};
    unique_ptr<string[]> arr {make_unique<string[]>(def_capacity)};
};

在我的实现文件中我有:

#include "StringSet.h"
#include <iostream>
#include <utility>

StringSet::StringSet(int capacity)
: arrSize{capacity},
    arr{make_unique<string[]>(capacity)}
{
}
StringSet::StringSet(const StringSet& a)
{
    auto a2 = StringSet(currentSize);
    for (auto i=0; i < currentSize ; i++ )
        {
        a2[i] = a[i];
        }
}

编译错误:

error: constructors may not be cv-qualified
error: no match for 'operator=' (operand types are 'StringSet' and 'std::string {aka std::basic_string<char>}')
error: passing 'const StringSet' as 'this' argument discards qualifiers [-fpermissive]
error: use of deleted function 'StringSet& StringSet::operator=(const StringSet&)'

我的赋值重载了赋值操作符=,因此我不能在这里使用它。有没有另一种不使用赋值操作符实现复制函数的方法——std::string中是否有任何东西允许我们以这种方式更容易地复制内容?

如果还有什么需要补充的,请告诉我。

谢谢。

这段代码的问题:

StringSet::StringSet(const StringSet& a)
{
    auto a2 = StringSet(currentSize);
    for (auto i=0; i < currentSize ; i++ )
    {
        a2[i] = a[i];
    }
}

是,即使它被编译了,你也从来没有真正初始化this的成员…您正在初始化一些在构造函数末尾超出作用域的临时a2。你需要:

StringSet::StringSet(const StringSet& a)
    : StringSet(a.arrSize)
{
    currentSize = a.currentSize;
    for (auto i=0; i < currentSize; i++ )
    {
        arr[i] = a.arr[i];
    }
}

另外,您的operator[]返回StringSet&,它可能应该返回std::string&

同样,您应该避免像您正在做的那样将名称引入全局命名空间。保持本地化。编写std::不是负担。