C++设置器函数崩溃



我有一个由两个不同类实例化的类,如下所示: 我在以下代码中遇到 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 类型的对象。

a._url_act_list为空。你可以

  • 定义接收大小的构造函数,并使用该大小创建vector(AB(
  • 或者在访问向量之前,即在for循环之前相应地resize向量
  • 或者只是将元素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真的应该公开吗?拥有URLAction(string s)构造函数不是更容易(考虑选项 3(吗?有些事情让我感到困扰,尽管这不是这个问题的一部分。

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

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

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]);

最新更新