gpt4 book ai didi

c++ - memcpy 是否保留了琐碎对象的有效性?

转载 作者:行者123 更新时间:2023-12-05 01:04:37 28 4
gpt4 key购买 nike

如果有一个普通类型的有效对象(在这种情况下,普通类型满足普通移动/复制可构造的概念),并且一个 memcpy 将它放到未初始化的内存区域,复制的内存区域是有效对象吗?

我读到的假设:一个对象只有在它的构造函数被调用时才有效。

最佳答案

使用 std::memcpy 将普通类型的对象复制到适当大小和对齐的存储中,将隐式地在该位置开始新对象的生命周期。

有一类类型称为 implicit-lifetime type其要求是:

  • a scalar type, or
  • an array type, or
  • an aggregate class type, or
  • a class type that has
    • at least one trivial eligible constructor, and
    • a trivial, non-deleted destructor,
  • or a cv-qualified version of one of above types.

Trivial class types满足这些要求。

隐式生命周期类型的对象具有 their lifetime can be started implicitly 的属性是几个函数或操作:

  • operations that begin lifetime of an array of type char, unsigned char, or std::byte, (since C++17) in which case such objects are created in the array,
  • call to following allocating functions, in which case such objects are
    • created in the allocated storage:
    • operator new
    • operator new[]
    • std::malloc
    • std::calloc
    • std::realloc
    • std::aligned_alloc (since C++17)
  • call to following object representation copying functions, in which case such objects are created in the destination region of storage or the result:
    • std::memcpy
    • std::memmove
    • std::bit_cast (since C++20)

关于c++ - memcpy 是否保留了琐碎对象的有效性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71835844/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com