gpt4 book ai didi

c++ - 是否需要显式构造 char 数组的每个成员?

转载 作者:行者123 更新时间:2023-12-02 20:12:07 25 4
gpt4 key购买 nike

考虑以下代码:

#include <memory>

template<typename Allocator>
char* allocate_array(Allocator alloc, size_t n)
{
static_assert(std::is_same<typename Allocator::value_type, char>::value);
char* data = alloc.allocate(n);

// (1)
for (size_t i=0; i<n; ++i) {
new (data+i) char();
}

return data;
}

char* copy_array(size_t n, const char* original)
{
char* copy = allocate_array(std::allocator<char>(), n);
// (2)
for (size_t i=0; i<n; ++i) {
copy[i] = original[i];
}
return copy;
}

即使保证每个字符都写入 (2),由 (1) 标记的放置新初始化是否有必要防止程序出现未定义的行为? code> 才能被读取?或者可以安全删除吗?

请注意,即使在 -O3 上,这也没有被优化掉,我看到 gcc 和 clang 都会生成对 memset()memcpy( )

最佳答案

Is the placement-new initialization marked by (1) necessary to prevent the program from having undefined behaviour.

据我所知,技术上是可以的。

[basic.life]

The lifetime of an object of type T begins when:

  • storage with the proper alignment and size for type T is obtained, and
  • its initialization (if any) is complete (including vacuous initialization) ([dcl.init]),

... before the lifetime of an object has started but after the storage which the object will occupy has been allocated or, after the lifetime of an object has ended and before the storage which the object occupied is reused or released, any glvalue that refers to the original object may be used but only in limited ways. ... The program has undefined behavior if:

  • the glvalue is used to access the object, or
  • ...
<小时/>

Note that this is not being optimized away

您可以默认初始化,而不是对字符进行值初始化。那么它们的值将在分配之前保持不确定,因此不需要 memset。另外,有一个标准函数可以实现此目的,因此无需编写循环:

std::uninitialized_default_construct(data, data + n);

关于c++ - 是否需要显式构造 char 数组的每个成员?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58417141/

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