c++ - 删除通过 memcpy 从字符串类复制的字符串时崩溃

标签 c++

我新建了一个字符串类,然后通过memcpy复制到另一个字符串类, 当我从另一个字符串类中删除它时它崩溃了。 有人可以帮忙解释一下吗? 谢谢


union Data {
    bool _bool;
    int16_t _int16;
    int32_t _int32;
    int64_t _int64;
    uint16_t _uint16;
    uint32_t _uint32;
    uint64_t _uint64;
    float _float;
    double _double;
    char s[sizeof(std::string)];
} ;

int main(int argc, char *argv[])
{
    Data d1;
    new(d1.s) std::string("123");

    Data d2;
    memcpy(d2.s, d1.s, sizeof(d1.s));

    void *p2 = d2.s;
    auto delStr2 = reinterpret_cast<std::string *>(p2);

    void *p1 = d1.s;
    auto delStr1 = reinterpret_cast<std::string *>(p1);

    delStr2->~basic_string();  //crashed

}

最佳答案

std::string 不是 trivially copyable type ,使用 memcpy 复制它会导致未定义的行为。

关于c++ - 删除通过 memcpy 从字符串类复制的字符串时崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58518704/

相关文章:

c# - 将 C++ 代码转换为 C# 用于加密算法

c++ - Linphone 编译 - Mingw 64 位 - 未找到 GNU gettext 工具;国际工具所需

c++将具有可变数量参数的函数作为参数传递给其他函数

c++ - 如何获得非常量迭代器

c++ - 覆盖 find_package 的默认搜索顺序

c++ - 能否从 DLL 中动态调用对象?

c++ - 重载类成员函数

c++ - Richedit Msftedit奇怪的边框

c++ - 用另一个 bool 值 boost 可选

c++ - 输出字符串时缺少第一个字符