My question:
Classes that contain only STL containers can use the Rule of Zero, and so avoid having to manually write the destructor/copies, etc.
I'm wondering if there's an STL tool (with the above property) designed for the simplest case: one element (on the heap)?
To explain when we'd want this:
Okay this problem is more niche/hypothetical: We've got an object Foo
with lots of members (n
members). Foo
gets move-copied a lot, so much that it's worthwhile storing its data as a single heap object (so instead of n
shallow copies it can do just 1
). It's also sometimes deep copied.
We can solve this by using vector
with one element:
class Foo
{
struct Data
{
char gender;
int age;
std::string name;
// lots of data
};
std::vector<Data> data;
public:
Foo () : data(1) {}
void Input (char c, int x, const std::string & str)
{
auto & d = data[0];
d.gender = c;
d.age = x;
d.name = str;
}
void Print () const
{
auto & d = data[0];
std::cout
<< d.gender << std::endl
<< d.age << std::endl
<< d.name << std::endl;
}
};
To avoid the constructor and all those [0]
s we could wrap the vector into its own class, but this feels like a hack - vector
is over-kill for this and could hold extra memory (size
and capacity
if the compiler doesn't optimise-out).
Note that unique_ptr
and shared_ptr
have different copy profiles to this, so aren't helpful here (example). Also, this problem is similar to but not quite the same as pimpl, because here we have a type that's defined (with pimpl we can't even use the above vector
technique).