Home > OS >  Is there some STL "container" for one element on the heap?
Is there some STL "container" for one element on the heap?

Time:09-22

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;
    }
};

demo

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).

CodePudding user response:

You are possibly looking for what is called deep/clone/copy/value pointer (basically a unique pointer with deep copy capabilities). There was even a proposal, don't know its actual status: http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2012/n3339.pdf.

AFAIK, it has not been accepted up to now. Maybe, some external library provides it (Boost?).

Relevant question: Is there a scoped ptr that has deep copy functionality built in? In its accepted answer, there is a link to some library, which should provide the required functionality. It doesn't seem to be any more maintained, but maybe it is still usable.

You can google for some more solutions. For instance, you can copy-paste (and possibly review) this implementation: https://vorbrodt.blog/2021/04/05/stddeep_ptr/.

I believe you can find some solutions on Code Reivew site as well, such as: DeepPtr: a deep-copying unique_ptr wrapper in C . I think it's a good idea to employ std::unique_ptr and just wrap it with the deep-copy functionality.

  • Related