“CopyConstructible” requirement for C++ stl container element

后端 未结 6 1150
后悔当初
后悔当初 2021-01-04 22:05

Regarding to the requirement for C++ stl container element, the standard says: the element type should be CopyConstructible, and there is a table for CopyConstructible requi

6条回答
  •  [愿得一人]
    2021-01-04 22:46

    In general, STL containers may copy your elements around at some stage, during some kinds of operations or algorithms, so the litmus test is:

    Element original(....);  // construct this awesome object
    original.this_and_that();  // do stuff to it until the value is perfect...
    
    Element another(original);
    

    Could you use another happily instead of original?

    That's effectively what the CopyConstructible requirement's saying: you better be able to have this copied into another object and still be happy with the result. It's not a draconian restriction - you just need to think it through and write your copy constructor correspondingly.

    But, it's significant in that some operations like find() may use == to compare elements (for other containers, it may be '<'), so if a side-effect of being copied is that you can't compare elements meaningfully, then your finds et al may stop working - think that through too! (The Standard says for containers, "== is an equivalence relation" (23.1-5).)

提交回复
热议问题