1

Is it possible to initialize a vector of vectors of non-copyable objects?

class obj : private boost::noncopyable {
    // ...
};

vector<vector<obj> > v(10); // OK
for(int i = 0; i < v.size(); ++i)
    v[i].resize(10); // ERROR

also

vector<vector<obj> > v(10, vector<obj>(10)); // ERROR

I understand why the above code won't compile. What I'm asking is whether there's a workaround. It seems that if std::vector had a member function like resize_from_zero that didn't need a copy constructor, then this would be doable.

(My question is about C++03, if this makes a difference)

MWB
  • 11,740
  • 6
  • 46
  • 91
  • 2
    Yes, it makes a difference - there are move semantics and `emplace_back` in C++11. – Columbo Nov 30 '14 at 19:56
  • Yes it's possible in C++11 - your code would only fail to work if the type was not default constructible and not movable. – Barry Nov 30 '14 at 19:57
  • If you use primitive types instead of obj. your code could work. But based on your question. You cannot do what you want. You either choose c++11 or you do some puch_bcck s. – BufBills Nov 30 '14 at 20:04
  • @BufBills You mean push_back's? Those need copy-constructors. – MWB Nov 30 '14 at 20:11
  • Just to be clear, would a C++11 approach that covers non-copyable non-movable objects be acceptable, or do you really need a C++03 approach? (I still don't think it would then work for `vector`, but a different container type might work.) –  Nov 30 '14 at 20:31

1 Answers1

2

This is not possible; C++03 requires that elements of a vector be CopyConstructible and Assignable.

Rreference: C++03 [lib.containers.requirements]/3

The type of objects stored in these components must meet the requirements of CopyConstructible types (20.1.3), and the additional requirements of Assignable types.

where "these components" means deque, list, queue, stack, vector, map, set, bitset.

(There may or may not be some way to have it appear to work on a particular compiler, but that is beyond the scope of Standard C++).

M.M
  • 138,810
  • 21
  • 208
  • 365