提交 54afca93 编写于 作者: H hsutter

Elaborated on PR #1539

上级 39b9ebdf
...@@ -6547,7 +6547,7 @@ That tends to work better than "cleverness" for non-specialists. ...@@ -6547,7 +6547,7 @@ That tends to work better than "cleverness" for non-specialists.
The standard C++ mechanism to construct an instance of a type is to call its constructor. As specified in guideline [C.41](#Rc-complete): a constructor should create a fully initialized object. No additional initialization, such as by `memcpy`, should be required. The standard C++ mechanism to construct an instance of a type is to call its constructor. As specified in guideline [C.41](#Rc-complete): a constructor should create a fully initialized object. No additional initialization, such as by `memcpy`, should be required.
A type will provide a copy constructor and/or copy assignment operator to appropriately make a copy of the class, preserving the type's invariants. Using memcpy to copy a non-trivially copyable type has undefined behavior. Frequently this results in slicing, or data corruption. A type will provide a copy constructor and/or copy assignment operator to appropriately make a copy of the class, preserving the type's invariants. Using memcpy to copy a non-trivially copyable type has undefined behavior. Frequently this results in slicing, or data corruption.
##### Example, bad ##### Example, good
struct base struct base
{ {
...@@ -6560,16 +6560,28 @@ A type will provide a copy constructor and/or copy assignment operator to approp ...@@ -6560,16 +6560,28 @@ A type will provide a copy constructor and/or copy assignment operator to approp
void update() override {} void update() override {}
}; };
##### Example, bad
void init(derived& a) void init(derived& a)
{ {
memset(&a, 0, sizeof(derived)); memset(&a, 0, sizeof(derived));
} }
This is type-unsafe and overwrites the vtable.
##### Example, bad
void copy(derived& a, derived& b) void copy(derived& a, derived& b)
{ {
memcpy(&a, &b, sizeof(derived)); memcpy(&a, &b, sizeof(derived));
} }
This is also type-unsafe and overwrites the vtable.
##### Enforcement
- Flag passing a non-trivially-copyable type to `memset` or `memcpy`.
## <a name="SS-containers"></a>C.con: Containers and other resource handles ## <a name="SS-containers"></a>C.con: Containers and other resource handles
......
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册