代码之家  ›  专栏  ›  技术社区  ›  Jake Petroules

内存清理问题将QString转换为char*以用于第三方库,如何解决?

  •  0
  • Jake Petroules  · 技术社区  · 14 年前

    char* 串。我使用以下代码将QString转换为

    char* toCharArray(const QString &string)
    {
        QByteArray bytes = string.toLocal8Bit();
        char* data = new char[bytes.count() + 1];
        strcpy(data, bytes.data());
        return data;
    }
    
    // later on...
    
    3rdPartyObject->3rdPartyMethod(toCharArray("someFile"));
    

    我能做些什么来确保 字符*

    char* path = toCharArray("someFile");
    3rdPartyObject->3rdPartyMethod(path); // The class and method called can differ
    delete[] path;
    
    2 回复  |  直到 14 年前
        1
  •  6
  •   Michael Anderson    14 年前

    为什么不用呢

    QString s;
    3rdPartyObject->3rdPartyMethod( s.toLocal8Bit().data() );
    

        2
  •  0
  •   Naveen    14 年前

    您可以使用智能指针,例如 boost::shared_ptr std::auto_ptr 因此,当智能指针超出范围时,内存将自动删除。