使用std :: wstring的Init结构

时间:2008-11-25 19:07:07

标签: c++ string structure

我的结构如下:

typedef struct
{
    std::wstring DevAgentVersion;
    std::wstring SerialNumber;

} DeviceInfo;

但是当我尝试使用它时,我会遇到各种内存分配错误。

如果我尝试将其传递给这样的函数:

GetDeviceInfo(DeviceInfo *info);

我会得到一个运行时检查错误,抱怨我在使用它之前没有初始化它,我似乎修复过:

DeviceInfo *info = (DeviceInfo*)malloc(sizeof(DeviceInfo));

但是,在函数中,当我尝试设置任何结构stings时,它会抱怨我在尝试为字符串设置值时尝试访问错误的指针。

初始化此结构的最佳方法是什么(以及所有内部字符串?

3 个答案:

答案 0 :(得分:9)

您应该使用new代替malloc,以确保为DeviceInfo及其包含的wstring调用构造函数。

DeviceInfo *info = new DeviceInfo;

通常,最好避免在C ++中使用malloc

此外,确保在使用完毕后delete指针。

编辑:当然,如果您只需要本地范围内的info,则不应在堆上分配它。只需这样做:

DeviceInfo info; // constructed on the stack
GetDeviceInfo( &info ); // pass the address of the info

答案 1 :(得分:1)

std :: wstring创建一个对象,并且需要构造对象。通过使用malloc,您绕过了结构的构造函数,其中包含所有成员的构造函数。

你得到的错误来自std :: wstring,试图使用一个仍然未初始化的成员。

您可以使用new而不是malloc,但最好的解决方案是使用本地临时变量并将其地址传递给函数。

DeviceInfo info;
GetDeviceInfo(&info);

答案 2 :(得分:1)

将函数添加到struct:

struct DeviceInfo
{
    std::wstring DevAgentVersion;
    std::wstring SerialNumber;
    WhatEverReturnType GetDeviceInfo() {
        // here, to your calculation. DevAgentVersion and SerialNumber are visible.
    }
};

DeviceInfo d; WhatEverReturnType e = d.GetDeviceInfo();

注意typedef struct {...}名称; C ++中不需要模式。如果由于某种原因必须使用免费功能,请使用参考:

WhatEverReturnType GetDeviceInfo(DeviceInfo &info) {
    // do your calculation. info.DevAgentVersion and info.SerialNumber are visible.
}

DeviceInfo d; WhatEverReturnType e = GetDeviceInfo(d);
相关问题