什么样的特征/概念可以保证对象的良好定义? [英] What trait / concept can guarantee memsetting an object is well defined?
问题描述
假设我已经定义了zero_initialize()
函数:
Let's say I have defined a zero_initialize()
function:
template<class T>
T zero_initialize()
{
T result;
std::memset(&result, 0, sizeof(result));
return result;
}
// usage: auto data = zero_initialize<Data>();
为某些类型调用zero_initialize()
会导致未定义的行为 1, 2 .我目前正在强制T
验证 std::is_pod
.随着C ++ 20中不赞成使用该特性以及概念的出现,我很好奇zero_initialize()
应该如何发展.
Calling zero_initialize()
for some types would lead to undefined behavior1, 2. I'm currently enforcing T
to verify std::is_pod
. With that trait being deprecated in C++20 and the coming of concepts, I'm curious how zero_initialize()
should evolve.
- 什么(最小)特征/概念可以确保对对象进行精确定义?
- 我应该使用
std::uninitialized_fill
而不是std::memset
吗?为什么? - 该函数是否由于一种类型子集的C ++初始化语法之一而过时?还是将来的C ++版本即将出现?
- What (minimal) trait / concept can guarantee memsetting an object is well defined?
- Should I use
std::uninitialized_fill
instead ofstd::memset
? And why? - Is this function made obsolete by one of C++ initialization syntaxes for a subset of types? Or will it be with the upcoming of future C++ versions?
1) 擦除类的所有成员.
2) 在库类(std :: string)上使用memset会导致未定义行为"的原因是什么? [关闭]
1) Erase all members of a class.
2) What would be reason for "undefined behaviors" upon using memset on library class(std::string)? [closed]
推荐答案
从技术上讲,C ++中没有对象属性,该属性指定用户代码可以合法地memset
C ++对象.其中包括POD,因此,如果您想成为技术专家,则代码永远是不正确的.甚至TriviallyCopyable都是关于在现有对象之间进行字节复制的属性(有时通过中间字节缓冲区);它没有说明发明数据并将其推入对象的位.
There is technically no object property in C++ which specifies that user code can legally memset
a C++ object. And that includes POD, so if you want to be technical, your code was never correct. Even TriviallyCopyable is a property about doing byte-wise copies between existing objects (sometimes through an intermediary byte buffer); it says nothing about inventing data and shoving it into the object's bits.
话虽如此,如果您测试is_trivially_copyable
和 is_trivially_default_constructible
,您可以合理地确定这将起作用.最后一个很重要,因为某些TriviallyCopyable类型仍然希望能够控制其内容.例如,这种类型可以具有始终为5的私有int
变量,该变量在其默认构造函数中初始化.只要没有可访问该变量的代码对其进行更改,它将始终为5.C++对象模型对此进行了保证.
That being said, you can be reasonably sure this will work if you test is_trivially_copyable
and is_trivially_default_constructible
. That last one is important, because some TriviallyCopyable types still want to be able to control their contents. For example, such a type could have a private int
variable that is always 5, initialized in its default constructor. So long as no code with access to the variable changes it, it will always be 5. The C++ object model guarantees this.
因此,您不能memset
这样的对象,仍然会从对象模型中获得明确定义的行为.
So you can't memset
such an object and still get well-defined behavior from the object model.
这篇关于什么样的特征/概念可以保证对象的良好定义?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!