【问题标题】:Init Structure with std::wstring带有 std::wstring 的初始化结构
【发布时间】:2008-11-25 19:07:07
【问题描述】:

我的结构如下:

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

} DeviceInfo;

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

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

GetDeviceInfo(DeviceInfo *info);

我会收到一个运行时检查错误,抱怨我在使用它之前没有对其进行初始化,我似乎已经解决了这个问题:

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

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

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

【问题讨论】:

    标签: c++ string structure


    【解决方案1】:

    您应该使用new 而不是malloc,以确保为DeviceInfo 及其包含的wstrings 调用构造函数。

    DeviceInfo *info = new DeviceInfo;
    

    一般来说,最好避免在 C++ 中使用malloc

    另外,请确保在使用完指针后delete

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

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

    【讨论】:

      【解决方案2】:

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

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

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

      DeviceInfo info;
      GetDeviceInfo(&info);
      

      【讨论】:

        【解决方案3】:

        将函数添加到结构中:

        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);
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2012-02-05
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2019-04-16
          • 1970-01-01
          • 2013-02-25
          • 1970-01-01
          相关资源
          最近更新 更多