trivially moveable but not trivially copyable

两盒软妹~` 提交于 2019-12-08 02:15:24

问题


Is it possible to make class type, which is:

  • trivially move-constructible, but not trivially copy-constructible, but still copy-constructible
  • trivially copy-constructible, but not trivially move-constructible, but still move-constructible
  • trivially copy-assignable, but not trivially move-assignable, but still move-assignable
  • trivially move-assignable, but not trivially copy-assignable, but still copy-assignable
  • trivially copy/move-constructible, but not trivially copy/move-assignable, but still copy/move-assignable and vice versa
  • etc (if any)

?

How they would look like?

The question make sense for developing, say, std::variant-like or std::tuple-like class.

The question is arised after looking through this article.


回答1:


To answer what I think is the heart of your question:

The question make sense for developing, say, std::variant-like or std::tuple-like class

There are 3 kinds of class-types that are of concern here viz.

  • Owner Types
  • Regular Types
  • Other types (Functions, Mutexes)

In the following assume both assign & construct suffixes are present for move/copy. I will refer to non-trivial operations as clone-:

Owner Types: These are Movable & Clone-able ( deep copy or shallow copy are the choices to be made) Stereotypical examples are std::unique_ptr, std::shared_ptr

Regular Types(int-like): These are Movable & Copy-able. Stereotypical examples are int, std::vector. A lot more details for these types can be found at What is a "Regular Type" in the context of move semantics? & in Elements Of Programming.

Other types (Functions, Mutexes etc.): These types refuse to be put into one of the clean classes above eg. Functions may refer to a pointer, a lambda with captures etc.

As far as all the other combinations of trivially copy-able/movable are concerned while you can create such classes I think they are more like curiosities rather things you will see in any useful scenario.

I have put std::vector in Regular Types rather than Owner Types even though std::vector manages memory since its interface is designed to be as close to a regular type as possible. You can often design a Regular interface for a type which is superficially non-regular. In such scenarios reasoning about code is easier if you use a regular interface.




回答2:


  1. yes
  2. yes
  3. yes
  4. yes

You'll need to be more clear on 5.

Trivial means (among other things) not user-provided. So simply explicitly writing the default implementation takes something from trivial to non-trivial.

http://eel.is/c++draft/class#class!trivially copyable

http://eel.is/c++draft/class.copy#25



来源:https://stackoverflow.com/questions/39607635/trivially-moveable-but-not-trivially-copyable

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!