2008-11-25 182 views
2

我有一个结构如下:初始化结构的std :: wstring的

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

} DeviceInfo; 

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

如果我尝试将其传递到这样的功能:

GetDeviceInfo(DeviceInfo *info); 

我会得到一个运行时检查错误抱怨我没有使用它,我似乎已经固定前初始化:

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

但随后,在功能,当我尝试设置任何结构刺的,它抱怨说,我想尝试设置值的字符串时访问一个坏的指针。

什么是初始化该结构的最佳方法(和它的所有内部字符串?

回答

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

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

你得到的错误是来自std :: wstring尝试使用其仍然未初始化的其自己的成员之一。

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

DeviceInfo info; 
GetDeviceInfo(&info); 
1

功能添加到结构:

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结构{...}名;模式在C++中是不需要的。如果由于某种原因必须使用免费功能,请参考:

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

DeviceInfo d; WhatEverReturnType e = GetDeviceInfo(d);