Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a C++ container with reasonable random access that never calls the element type's copy constructor?

Tags:

c++

stl

I need a container that implements the following API (and need not implement anything else):

class C<T> {
  C();

  T& operator[](int); // must have reasonably sane time constant

    // expand the container by default constructing elements in place.
  void resize(int); // only way anything is added.
  void clear();

  C<T>::iterator begin();
  C<T>::iterator end();
}

and can be used on:

class I {
 public:
  I();
 private:  // copy and assignment explicate disallowed
  I(I&);
  I& operator=(I&);
}

Dose such a beast exist?

vector<T> doesn't do it (resize moves) and I'm not sure how fast deque<T> is.


I don't care about allocation

Several people have assumed that the reason I can't do copies is memory allocation issues. The reason for the constraints is that the element type explicitly disallows copying and I can't change that.


Looks like I've got my answer: STL doesn't have one. But now I'm wondering Why not?

like image 996
BCS Avatar asked Nov 30 '22 10:11

BCS


2 Answers

I'm pretty sure that the answer here is a rather emphatic "No". By your definition, resize() should allocate new storage and initialize with the default constructor if I am reading this correctly. Then you would manipulate the objects by indexing into the collection and manipulating the reference instead of "inserting" into the collection. Otherwise, you need the copy constructor and assignment operator. All of the containers in the Standard Library have this requirement.

You might want to look into using something like boost::ptr_vector<T>. Since you are inserting pointers, you don't have to worry about copying. This would require that you dynamically allocate all of your objects though.

like image 190
D.Shawley Avatar answered Dec 05 '22 07:12

D.Shawley


You could use a container of pointers, like std::vector<T*>, if the elements cannot be copied and their memory is managed manually elsewhere.

If the vector should own the elements, something like std::vector< std::shared_ptr<T> > could be more appropriate.

And there is also the Boost Pointer Container library, which provides containers for exception safe handling of pointers.

like image 31
sth Avatar answered Dec 05 '22 07:12

sth