【发布时间】:2020-01-15 08:06:47
【问题描述】:
以下代码块正在编译和运行正常。
Qeus-1。 memset 一个包含另一个以智能指针作为成员变量的结构的结构是否安全? (就像下面的示例代码)
问题 2。 memset 包含智能指针成员的结构是否安全?
以下代码结构是遗留项目的一部分,其中这种分层结构有数百个其他成员(POD 或非 POD 成员)
#include <iostream>
#include <map>
#include <string>
#include <string.h>
#include <stdlib.h>
#include <memory>
typedef struct _Globals{
std::shared_ptr<std::map<int, std::string> > rollNamePair;
} _Globals;
struct _Class {
struct _Globals Globals; // global vars
};
struct _School {
struct _Class *pSchool;
};
int main()
{
struct _School abc;
memset(&abc, 0, sizeof(struct _School));
abc.pSchool= (struct _Class*) malloc(sizeof(struct _Class));
abc.pSchool->Globals.rollNamePair= std::make_shared<std::map<int, std::string> >();
(*abc.pSchool->Globals.rollNamePair)[1]= "John";
(*abc.pSchool->Globals.rollNamePair)[2]= "Paul";
std::cout << (*abc.pSchool->Globals.rollNamePair)[1] << "\n";
std::cout << (*abc.pSchool->Globals.rollNamePair)[2];
return 0;
}
【问题讨论】:
-
不,
malloc()和struct与带有构造函数的成员一起使用也不安全! -
_School不包含智能指针,它包含一个原始指针。 -
顺便说一下,这里不需要
typedefs 和一半的structs。 -
@Evg,标题已更新
-
还有像
_Globals和_School这样的名称是保留的。也许您是通过查看您的实现标准库来了解它的,它使用像这样丑陋的名称因为它们是为它保留的。