【发布时间】:2013-07-16 00:13:20
【问题描述】:
首先,我是 c++ 和 list 的新手,所以它可能很明显,我只是没看到,抱歉 :(
我正在尝试创建文件列表,当我尝试将第一个文件推送到列表时遇到错误。调试断言错误消息是“列表插入迭代器超出范围”。
在头文件中,我有:
class ConfigDefFile
{
public:
ConfigDefFile( const char * dir_path, const char * file_name );
private:
ConfigDef * config;
static char filePath[ MAX_PATH + 1 ];
};
typedef list<ConfigDefFile *> ConfigDefFileList;
ConfigDefFileList def_files;
我将文件添加到列表的代码是:
char * root_path = NULL;
ConfigDefFile * def_file;
root_path = GetDefDir(); //Gets the root directory for the file.
def_file = new ConfigDefFile( root_path, file );
def_files.push_back( def_file ); //error occurs here
关于我正在做什么会导致这种情况的任何想法?
【问题讨论】:
-
请使用 std::string 代替 const char*
-
较大的应用程序与 C 代码交互,所以我更喜欢 char * 以保持一致性/可读性...
-
一致性是一个很好的理由,但是 a) std::string 会为您省去很多麻烦 b) 如果您需要 const char*,只需调用 c_str() 方法。
-
我有根据的猜测是,您设法在未显示的代码中的某处破坏了堆。 list::push_back 是一个无辜的旁观者,刚好踩到了别处埋下的地雷。
-
使用
list<ConfigDefFile>,而不是指针列表。您使用的指针越少,您就越快拥有一个无错误的程序,