C++ setter 函数崩溃

Crash in C++ setter function

我有一个 class 由两个不同的 class 实例化,如下所示: 我在以下代码中遇到 set_url() 函数崩溃。无法决定为什么?

class UrlAction {
    String url;
    bool action;
public:
   UrlAction() : action(false) {};

   void operator=(const UrlAction &from);

   inline String get_url() {
       return url;
   }
   inline void set_url(String from_url) {
       this->url = from_url;
   }
   inline bool get_action() {
       return action;
   }
   inline void set_action(bool act) {
       this->action = act;
   }
};

class A {
public:
    Vector<UrlAction>   _url_act_list;
};
class B {
public:
    Vector<UrlAction>   _url_act_list;
};
foo() {
    A a;
    B b;
    Vector<String> temp_vect;
    temp_vect.push_back("xxxxx.com");
    temp_vect.push_back("yyyyy.com");
    temp_vect.push_back("zzzzz.com");
    temp_vect.push_back("wwwww.com");
    temp_vect.push_back("vvvvv.com");

    for (int i = 0; i < temp_vect.size(); i++) {
        a._url_act_list[i].set_url(temp_vect[i]); //This is the line causing crash
    }
}

我还编写了一个“=”运算符重载程序,用于分配两个 UrlAction 类型的对象。

Vector<UrlAction> _url_act_list在声明a时实例化,但_url_act_list的大小最初为0。因此,当您尝试对其进行索引时,您会遇到导致程序崩溃的段错误。

a._url_act_list 为空。你可以

  • 要么定义一个接收大小的构造函数,然后使用该大小创建 vector(在 AB 中)
  • resize 向量相应地在访问它之前,即在 for 循环之前
  • 或者只是push_back向量中的元素

第一个选项可能如下所示:

A::A(size_t size) : { _url_act_list.resize(size) }
B::B(size_t size) : { _url_act_list.resize(size) }

第二个选项可能如下所示:

a.resize(temp_vect.size());
for (int i = 0; i < temp_vect.size(); i++) {
    a._url_act_list[i].set_url(temp_vect[i]); //This is the line causing crash
}

第三个选项可能如下所示:

for (int i = 0; i < temp_vect.size(); i++) {
    UrlAction url_action;
    url_action->set_url(temp_vect[i]);
    a._url_act_list.push_back(url_action); //This is the line causing crash
}

我相信你的代码可能设计得更好。 _url_act_list 真的应该是 public 吗?拥有一个 URLAction(string s) 构造函数不是更容易(考虑选项 3)吗?虽然这不是这个问题的一部分,但有些事情让我很烦恼。

a._url_act_list 当您尝试为它调用 operator[] 时,它是空的。考虑更换

a._url_act_list[i].set_url(temp_vect[i]); //This is the line causing crash

a._url_act_list.push_back({});
a._url_act_list.back().set_url(temp_vect[i]);