【发布时间】:2021-11-28 14:41:00
【问题描述】:
基本上我正在尝试实现我自己的类似于矢量的数据类型。我这样做只是为了好玩。问题是我在尝试放置 string 类型的新元素时经常遇到 Segmentation fault (试图创建一个名为 person 的结构并且它有一样的问题)。我认为在这种情况下最重要的一段代码(table.h):
template<typename type>
class table
{
private:
type* elements = new type[0];
unsigned int length_ = 0;
void resize(int change)
{
length_ = length_ + change;
type* elements_ = new type[length_];
std::memcpy(elements_, elements, length_ * sizeof(type));
delete[] elements;
elements = elements_;
}
public:
/* ... */
void put(type&& element)
{
resize(1);
elements[length_ - 1] = element;
}
}
然后(main.cpp):
/* ... */
int main()
{
table<string> t;
t.append("Hello World"); // segfault
for(string s : t) {cout << s << endl;}
/* But this works:
table<char*> t;
t.append((char*)"Hello World");
for(string s : t) {cout << s << endl;} */
}
【问题讨论】:
-
提供的代码不会重现所描述的问题。并且
std::memcpy正在用于非 memcpy-able 对象。 -
不要使用
new:使用std::vector。我从未见过在初始化语句中使用new。它可能有效,也可能无效。 -
您不能在
string等一般类型上使用memcpy。大致而言,string包含一个指向实际字符串数据所在的 char 的指针。如果我们memcpy,我们会得到两个具有相同指针的字符串,然后当两者都被破坏时,我们会对同一个指针执行双重释放,这是未定义的行为。memcpy只对非常基本的数据类型是安全的。 -
查看相关question。