我有一个C ++程序,如下所示。我试图通过值将std :: list从一个函数传递给另一个函数。我希望通过迭代器在调用函数中访问列表?我希望return将调用std::list
的复制构造函数,并且可以在调用者中访问它。我的假设错了吗?如果不是为什么我会遇到分段错误。
#include <list>
#include <map>
#include <string>
#include <set>
#include <iterator>
#include <iostream>
const char *sy_path = "/var/log";
struct Setting
{
typedef std::list<const Setting*> List;
const char* path;
const char* filename;
const char* name;
int def;
int min;
int max;
struct Original
{
const char* filename;
const char* name;
Original(const char* filename_, const char* name_)
:filename(filename_), name(name_)
{
}
}original;
static const List settings();
};
const Setting::List Setting::settings()
{
const Setting c_settings[] =
{ //default min max
{ sy_path, "cs.cfg", "num_a", 1, 1, 29, Original("sys.cfg", "num_a") }
,{ sy_path, "cs.cfg", "num_b", 1, 1, 6, Original("sys.cfg", "num_b") }
,{ sy_path, "cs.cfg", "num_c", 1, 1, 29, Original("sys.cfg", "num_c") }
};
Setting::List lst;
int numelem = sizeof(c_settings) / sizeof(Setting);
for (int i = 0; i < numelem; i++)
{
const Setting & tmpSetting = c_settings[i];
lst.push_back(&tmpSetting);
}
return lst;
}
static int get_settings(void)
{
Setting::List lst;
lst = Setting::settings();
for (Setting::List::const_iterator it = lst.begin() ; it != lst.end(); ++it)
{
const Setting *cs = *it;
std::cout << "path: " <<cs->path << "filename: " <<cs->filename << "name: " << cs->name << std::endl;
}
}
int main()
{
get_settings();
return 0;
}
答案 0 :(得分:1)
是的,return lst;
将返回lst
的副本。问题是你将lst
指针放在堆栈上的数据(const Setting c_settings[]
变量)。从函数返回后,这些指针变为无效,因此出现分段错误。解决方案是为堆上的设置分配内存,或使用std::list<Setting>
。
typedef std::list<Setting> List;
lst.push_back(c_settings[i]); // make sure you have the right copy constructor
或
lst.push_back(new Setting(c_settings[i])); // make sure you have the right copy constructor
另外,我会避免使用const char *
并改为使用std::string
。