我写了一个示例代码,当列表 push_back 时它总是导致 coredump 这是我的代码:
#include <iostream>
#include <list>
#include <string.h>
using namespace std;
struct FDTinstance
{
int type;
unsigned int expirestime;
unsigned int fileTOI;
string filename;
unsigned int contentlength;
unsigned long long T3;
unsigned long long T1;
unsigned long long T4;
unsigned long long sessionstarttime;
};
struct PacketInfo
{
unsigned int port;
unsigned long long arrivetime;
unsigned int syncType;
unsigned short timeStamp;
unsigned short packNum;
unsigned int packCount;
unsigned int TSI;
unsigned int TOI;
FDTinstance fDTinstance;
};
int main(int argc, char* argv[])
{
struct PacketInfo packet;
packet.fDTinstance.filename = "http://123.com";
packet.syncType=1;
packet.fDTinstance.expirestime = 100;
packet.fDTinstance.fileTOI = 0;
struct PacketInfo pack;
memcpy(&pack, &packet, sizeof(packet));
mVodList.push_back(pack);//cause core
return 0;
}
如果我使用 const char* filename
,程序就可以了。但是当我使用字符串类型时,程序将以 push_back()
为核心。我不知道为什么。谢谢
最佳答案
只需删除 memcpy
并执行此操作:
PacketInfo pack = packet;
或者更好的是,完全忘记中间拷贝并执行此操作:
mVodList.push_back(packet); // stores a copy of packet
原因是 memcpy
只适用于 POD 类型,而 std::string
不是其中之一。在任何情况下,即使对于 POD,使用复制构造函数或赋值运算符也是将一个对象复制到另一个对象的惯用方法。
另请注意,在 C++ 中,您不需要在整个地方编写 struct
。那为什么这么说
struct PacketInfo packet;
什么时候可以说?
PacketInfo packet;
关于c++ - 列出 push_back 一个包含字符串类型核心的结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18182405/