c++ - Copy constructors with move-only, but cloneable types in member containers -
assume have 2 types, t1
, t2
.
t1
isn't important except following facts:
- it isn't copy constructible
- it has move constructor
- we have excellent function signature
t1 copy(t1 const& orig)
, creates copy.
t2
can simplified following class:
// t2.h class t2 { public: t2() { /* initializes vector */ } t2(t2 const& other); private: std::vector<t1> v; } // t2.cpp t2::t2(t2 const& other) : ... {}
how implement method, if write ellipsis part, or global scope?
a simple real world use case - assuming "you can't write between curly braces" part real world restriction:
t1
std::unique_ptr<anything>
copy
std::make_unique
anything
has copy constructor
i have 2 additional requirements implementation:
- performance. shouldn't (considerably) slower naive implementation
for
loop in copy constructor's body. - readability. entire point behind question more clear/clean trivial loop (e.g. imagine t2 2 or more member vectors).
and optional, nice have features:
- something that's generalized other containers
- something works iterators
- something that's generic
a clarification: know question trivially solvable std::vector<t1> copy_vec(std::vector<t1> const& orig)
global function. placing function anonymous namespace within t2.cpp
make local, argue against readability, think wouldn't better loop @ all. , it's bad solution if copy constructor isn't in implementation file inlined in header.
so rephrasing of question is:
- is there similar implemented, can include?
- if there none, why? i'm not saying thought every corner case, think possibly can implemented in nice generic way, ,
unique_ptr
, it's common enough case.
nothing wrong naive loop:
v.reserve(other.v.size()); (auto& elem : other.v) { v.push_back(copy(elem)); }
that's plenty readable , optimal.
though guess modern, clever solution use range-v3:
t2(t2 const& other) : v(other.v | view::transform(copy)) { }
i'm not sure that's enough better loop justify additional complexity ymmv.
Comments
Post a Comment