【发布时间】:2020-03-04 07:18:57
【问题描述】:
我有一些自编向量的训练示例,为了简单起见,它不是模板:
class UglyStringsVector {
public:
UglyStringsVector() = default;
explicit UglyStringsVector(size_t size);
UglyStringsVector(const UglyStringsVector&);
~UglyStringsVector();
std::string &operator[](size_t index);
std::string *begin();
std::string *end();
const std::string *begin() const;
const std::string *end() const;
size_t Size() const;
size_t Capacity() const;
void PushBack(std::string value);
void operator=(const UglyStringsVector &other);
private:
std::string *data = nullptr;
size_t size = 0;
size_t capacity = 0;
void ExpandIfNeeded();
};
赋值运算符没有正确实现:
UglyStringsVector& UglyStringsVector::operator=(const UglyStringsVector &other) {
delete[] data;
data = new std::string[other.capacity];
size = other.size;
capacity = other.capacity;
copy(other.begin(), other.end(), begin());
return *this;
}
正如我们在这里看到的,当this == &other(我不是故意检查这个条件)时,它会删除自己的记忆(当然这是错误的),然后在同一个地方重新分配新的字符串(data = new std::string[other.capacity];),字符串不会未初始化,因为在operator new[]期间调用了默认构造函数,然后将字符串复制到自己(copy(other.begin(), other.end(), begin());)。
让我们想象一下失去记忆不是问题:-) 有人对我耳语说,将内存复制到自身是未定义的行为,但我不确定。 问题:是否有任何未定义的行为?
【问题讨论】:
-
@Bob__ 感谢您的回答,但我知道复制和交换,并且知道我的代码根本不正确))问题是关于合成示例中未定义的行为......
-
请参阅 The rule of three/five/zero 了解有关复制/分配的提示。
标签: c++ new-operator undefined-behavior delete-operator assignment-operator