2008-11-25 53 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);