gpt4 book ai didi

C++类指针删除段错误

转载 作者:太空宇宙 更新时间:2023-11-04 15:27:57 25 4
gpt4 key购买 nike

我有一个名为 object 的简单类,但我遇到了问题。如果我调用它,有一种方法会导致段错误。我不明白为什么。

typedef class object
{
private:
short id;
std::string name;
SDL_Rect offset;

public:
object();
object(short i, std::string n);
~object();
object(const object &o);
object& operator = (const object &o);
std::string get_name();
void set_name(std::string n);
} object;

object::object()
{
id = 0;
name = "";
offset.x = 0;
offset.y = 0;
offset.w = 0;
offset.h = 0;
}

object::object(short i, std::string n)
{
id = i;
name = n;
offset.x = 0;
offset.y = 0;
offset.w = 0;
offset.h = 0;
}

object::~object()
{
delete &offset;
delete &id;
delete &name;
}

object& object::operator=(const object &o)
{
if(this != &o)
{
delete &name;
name.assign(o.name);
delete &id;
id = o.id;
delete &offset;
offset = o.offset;
}
return *this;
}

object::object(const object &o)
{
id = o.id;
name = o.name;
offset = o.offset;
}

// Functions
std::string object::get_name()
{
return name;
}

void object::set_name(std::string n)
{
name = n;
}

还有我的 main.cpp

int main( int argc, char** argv )
{
struct object *a = new object(0, "test");
struct object *b = new object(1, "another test");

printf(a->get_name().c_str());
printf("\n");
printf(b->get_name().c_str());
b = a;
printf("\n");
printf(b->get_name().c_str());
a->set_name("Another test");
printf("\n");
printf(a->get_name().c_str());

delete a;
printf("\nDeleted a");
delete b;
printf("\nDeleted b");

return 0;
}

如果我调用 a->set_name("Another test");,我会遇到段错误。如果我不接电话,没问题,一切正常。我可能遗漏了一些简单的东西,但我找不到。它不会在分配上出现段错误,但如果该行存在,则在删除指针时会崩溃。

最佳答案

因为您没有在构造函数中new任何东西,所以在析构函数中delete任何东西都是错误的。将析构函数留空,或者更好的是,完全摆脱它。编译器生成的析构函数完全符合您的要求(什么都不做)。您也不必手动编写复制构造函数和复制赋值运算符,只需将它们扔掉即可。

也不需要动态创建对象,并且使用 native C++ 输入/输出工具打印字符串要容易得多。你可以摆脱使用默认参数重载构造函数。通过引用到常量传递和返回字符串比通过值传递它们更有效。最后但同样重要的是,让我们保持正确。这是我对您的代码的清理:

#include <iostream>

class object
{
short id;
std::string name;
SDL_Rect offset;

public:

object(short i = 0, const std::string& n = "");
const std::string& get_name() const;
void set_name(const std::string& n);
};

object::object(short i, const std::string& n) : id(i), name(n)
{
offset.x = 0;
offset.y = 0;
offset.w = 0;
offset.h = 0;
}

const std::string& object::get_name() const
{
return name;
}

void object::set_name(const std::string& n)
{
name = n;
}

int main(int argc, char** argv)
{
object a(0, "test");
object b(1, "another test");

std::cout << a.get_name() << "\n";
std::cout << b.get_name() << "\n";

b = a;
std::cout << b.get_name() << "\n";

a.set_name("Another test");
std::cout << a.get_name() << "\n";
}

关于C++类指针删除段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4016587/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com