Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"CopyConstructible" requirement for C++ stl container element

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 requirements. Also by various books (Josuttis, etc.), the generated copy should be "equivalent to" the source.

I think I need some clarity here. What is exactly "equivalent to"? Also I am a bit confused with the relation between the "CopyConstructible" and the "deep/shallow copy". In general, a copy constructor is either shallow copy or deep copy. So which one applies to the "CopyConstructible", and which does not?

Thanks for any comments!

like image 800
pepero Avatar asked Jun 30 '11 08:06

pepero


People also ask

How are STL containers implemented in C++?

They are implemented as class templates, which allows great flexibility in the types supported as elements. The container manages the storage space for its elements and provides member functions to access them, either directly or through iterators (reference objects with similar properties to pointers).

What is an STL container C++?

An STL container is a collection of objects of the same type (the elements). Container owns the elements. Creation and destruction is controlled by the container.

Which of the following are STL containers types?

The three types of containers found in the STL are sequential, associative and unordered.


2 Answers

Deep or shallow copy both work. For instance, shared_ptr always does a shallow copy (with some extra reference counting stuff), and you can use them in containers just fine. It depends on the semantics of copy-operation.

Equivalent means your program should not depend on whether it works with the original or with the copy.

like image 162
Björn Pollex Avatar answered Sep 21 '22 13:09

Björn Pollex


If you put something into a container, when you retrieve it you will get something that is equivalent to what you put in. So long as that is meaningful for your objects then you will get out something useful from the container.

Whether that is a shallow or deep copy depends on the semantics that you want for your object type. Your object might be pointer-like, handle-like or perhaps container like. It might contain some mutable cache data that you may or may not choose to duplicate on a copy operation.

So long as your copy constructor is accessible and does what you need it to do to preserve the semantics of your object type then you satisfy the CopyConstructible requirement.

like image 24
CB Bailey Avatar answered Sep 24 '22 13:09

CB Bailey