c++ - 列出 push_back 一个包含字符串类型核心的结构

标签 c++ string stl

我写了一个示例代码,当列表 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/

相关文章:

c++ - C++ 内置库中的多态性示例?

c++ - 为什么 `std::all_of` 不使用 `std::invoke` ?

c++ - 如何使用指针打印数组?

c++ - 整数如何存储在内存中?

string - 如何在Dart中替换字符串中所有字符(空格字符除外)

java - 如何在 Java 中比较字符串?

c++ - C++ 头文件如何包含实现?

c++ - 初始化顺序和移动语义

ios - 如何通过标题的第一个字母创建字典但忽略 "the"或 "a/an"等文章

c++ - vector 的 STL vector - 好主意吗?调整 "inner" vector 大小的机制?