On Monday, 27 March 2023 at 23:11:53 UTC+3, Pawel Por wrote:
> Hello,
>
> Assume there is a struct with a single member object. When creating the object of a struct I want the member object sometimes be copied and sometimes moved. Is the following approach correct ? Assume I don't want to use generic programing.
>
Note that destructor of Item is missing. In your example (that does nothing)
it does not matter, but in real class it should be always present when you
define any of assignment, move or copy construction. It is called "Rule of
zero, three or five".
Your Container lacks all of 5 (that is OK) but has implicit copy and move
conversion constructors from other class. That can cause confusion.
Perhaps do not use examples that do nothing. You may fail when you
attempt to write programs that do something.
Yes, your main() compiles but most compilers optimise all the code out of
it as it does nothing externally observable. IOW copying or moving has
only any point when there is something to copy or to move and that is used
for something meaningful. Note that also such code compiles (and does also
nothing, and so is as meaningless):
Item a;
Container cont = a;
Container cont2 = std::move(a);
cont = cont2;
cont = std::move(cont2);
cont2 = a;
cont2 = std::move(a);