c++ - 在方法中带有自定义对象 : crash when I want to use one received with . 的 vector

标签 c++

我有一个名为 CConfig 的类,我正在创建新对象:

std::vector< CConfig > docs;

CConfig newfile( "somefile.xml", "root" );
printf("%s", newfile.GetTagValue( "servername" )); // this works
docs.push_back( newfile );

当我使用 .at 方法获取此对象时

CConfig file = docs.at(0);
printf("%s", file.GetTagValue( "servername" )); // this crashes

问题出在哪里?

(很抱歉,如果格式错误,但目前我不使用 javascript,因为我的带宽已结束且最大速度为 1kb/s,所以我稍后会尝试修复它)

CConfig.h:

class CConfig
{
    TiXmlDocument       m_doc;
    TiXmlElement*       m_pRoot;
    bool                m_bIsLoaded;

public:
                    CConfig                     ( void ) {};
                    CConfig                     ( const char * pszFileName, const char * pszRootName );
                    ~CConfig                    ( void ) {};

const char*         GetTagValue                 ( const char * pszTagName );
const char*         GetTagAttribute             ( const char * pszTagName, const char * pszAttributeName );
TiXmlElement*       GetRootElement              ( void )    { return m_pRoot; };
bool                IsAvailable                 ( void )    { return m_bIsLoaded; };
};

CConfig.cpp

#include "CConfig.h"

CConfig::CConfig( const char * pszFileName, const char * pszRootName )
{
    m_bIsLoaded = m_doc.LoadFile( pszFileName );
    if( m_bIsLoaded )
        m_pRoot = m_doc.FirstChildElement( pszRootName );
}

const char * CConfig::GetTagValue( const char * pszTagName )
{
    if( m_bIsLoaded && m_pRoot )
    {
        TiXmlElement * element = m_pRoot->FirstChildElement( pszTagName );
        if( element )
            return element->GetText();
    }
}

const char * CConfig::GetTagAttribute( const char * pszTagName, const char * pszAttributeName )
{
    if( m_bIsLoaded && m_pRoot )
    {
        TiXmlElement * element = m_pRoot->FirstChildElement( pszTagName );
        if( element )
            return element->Attribute( pszAttributeName );
    }
}

我正在使用 tinyxml

最佳答案

您的问题是指向旧内存的指针。当您将项目添加到数组时,它会被复制。后来你离开那个范围,原来的被销毁了,但问问你自己,你的拷贝中的指针指向哪里?仍然是第一个(现已删除)对象的内存。呃哦。

最简单的修复(同时避免大量复制操作)是将 m_doc 变成共享指针(在 C++11 的标准中可用,或通过 C++03 中的 Boost)。然后,这将根据 3 条规则为您处理所有事情。由于底层内存不会移动,m_pRoot 将保持有效,直到最后一个拷贝被删除。

关于c++ - 在方法中带有自定义对象 : crash when I want to use one received with . 的 vector ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18166218/

相关文章:

c++ - 在 C++ 中执行默认的 catch throw 语句按值或引用传递

C++ makefile - 链接器找不到外部库

c++ - 编写二进制文件模板函数

c++ - 初始化一个未知大小的数组

C++ 构造函数运行时/编译时

c# - 将可变大小的 double 组从 C++ 返回到 C# - 一种更简单的方法?

c++ - xcode 解决方案的 node-gyp 链接问题

c++ - 使用 GCC 扩展定义

c++ - 手动创建PE

c++ - 如何避免 C++11 中 <thread> 抛出的异常?