提问人:simd 提问时间:9/8/2023 更新时间:9/8/2023 访问量:123
为什么 std::vector 在调整大小时不使用 memcpy 或 realloc
Why std::vector doesn't use memcpy or realloc when resizing
问:
我了解到它会在调整大小时显式调用每个元素的复制构造函数,如果我理解正确的话,这意味着它不使用或在引擎盖下,这是我的第一个假设。我的理解正确吗?如果是这样,为什么他们需要以这种方式实现,而不是更好的是,在引擎盖下调整动态阵列大小的最快选择?std::vector
memcpy
realloc
std::vector
memcpy
realloc
答:
为某个类型使用显式复制构造函数的根本原因是,复制位不适用于该类型。因此,C++ 容器操作是在复制构造方面指定的。这并不意味着禁止复制 -able 类型的位;符合要求的程序无法检测值是通过赋值还是通过赋值复制的。事实上,如果你研究一下 std::copy
的实现,它们通常会用于内置类型。memcpy
int
memcpy
memcpy
评论
memcpy
struct Foo { Foo() : ptr(&x) {}; int x; int *ptr; }
noexcept
The official declaration of is:std::vector
template< typename T,
typename Alloc = std::allocator<T> >
class std::vector;
The allocator parameter - like any other STL container - has a default instance of . This 2nd argument of the container controls the life-time (alloc/dealloc, construct/destroy) of the elements. The default allocator just may or may not use as the implementation of hint version of its member function.
Copying data in C++ involves a lot of consideration. In general it is bad practice to use explicitly for this purpose. If the object to be copied - or any none-static data members or base base classes - provides user-defined copy constructor() and/or copy assignment operator(), then bitwise copy performed by leads to wrong results, possibility involving UB and all sort bugs. If on the other hand the type is trivially copyable, compiler is free to perform all sort of optimizations, including for copying on the type.
The keeps one data member of its allocator type, in case the allocator is not an empty type( the default type is empty and uses empty allocator optimization). So if special treatment of memory is needed, user can provide his own version of allocator (which may hold state variables per instance) to STL class:std::allocator
std::realloc
allocate
std::memcpy
T::T(T const&)
T& T::operator(T&)
memcpy
memcpy
std::vector
struct my_T_alloc;//provide the definitions
struct my_T;//define the type
std::vector<my_T, my_T_alloc> m_T_vec;
The custome allocator should provide the corresponding memeber functions of std::allocator_traits
.
评论
struct Foo { Foo() : ptr(&x) {}; int x; int *ptr; }
memcpy
ptr
push_back
vector<Foo>
std::vector
memcpy
realloc
realloc
realloc
std::vector
memcpy()
realloc()
memcpy()
realloc()
memcpy()
realloc()