<p>As a general rule, I prefer using value rather than pointer semantics in C++ (ie using <code>vector&lt;Class&gt;</code> instead of <code>vector&lt;Class*&gt;</code>). Usually the slight loss in performance is more than made up for by not having to remember to delete dynamically allocated objects.</p>

<p>Unfortunately, value collections don't work when you want to store a variety of object types that all derive from a common base. See the example below.</p>

<pre><code>#include &lt;iostream&gt;

using namespace std;

class Parent
{
    public:
        Parent() : parent_mem(1) {}
        virtual void write() { cout &lt;&lt; "Parent: " &lt;&lt; parent_mem &lt;&lt; endl; }
        int parent_mem;
};

class Child : public Parent
{
    public:
        Child() : child_mem(2) { parent_mem = 2; }
        void write() { cout &lt;&lt; "Child: " &lt;&lt; parent_mem &lt;&lt; ", " &lt;&lt; child_mem &lt;&lt; endl; }

        int child_mem;
};

int main(int, char**)
{
    // I can have a polymorphic container with pointer semantics
    vector&lt;Parent*&gt; pointerVec;

    pointerVec.push_back(new Parent());
    pointerVec.push_back(new Child());

    pointerVec[0]-&gt;write(); 
    pointerVec[1]-&gt;write(); 

    // Output:
    //
    // Parent: 1
    // Child: 2, 2

    // But I can't do it with value semantics

    vector&lt;Parent&gt; valueVec;

    valueVec.push_back(Parent());
    valueVec.push_back(Child());    // gets turned into a Parent object :(

    valueVec[0].write();    
    valueVec[1].write();    

    // Output:
    // 
    // Parent: 1
    // Parent: 2

}
</code></pre>

<p>My question is: Can I have have my cake (value semantics) and eat it too (polymorphic containers)? Or do I have to use pointers?</p>

[{'answer_id': 41059, 'author': '1800 INFORMATION', 'author_id': 3146, 'author_profile': 'https://Stackoverflow.com/users/3146', 'pm_score': 6, 'selected': True, 'text': '<p>Since the objects of different classes will have different sizes, you would end up running into the slicing problem if you store them as values.</p>\n\n<p>One reasonable solution is to store container safe smart pointers. I normally use boost::shared_ptr which is safe to store in a container. Note that std::auto_ptr is not.</p>\n\n<pre><code>vector&lt;shared_ptr&lt;Parent&gt;&gt; vec;\nvec.push_back(shared_ptr&lt;Parent&gt;(new Child()));\n</code></pre>\n\n<p>shared_ptr uses reference counting so it will not delete the underlying instance until all references are removed.</p>\n'}, {'answer_id': 41074, 'author': '17 of 26', 'author_id': 2284, 'author_profile': 'https://Stackoverflow.com/users/2284', 'pm_score': 2, 'selected': False, 'text': "<blockquote>\n  <p>Take a look at <em>static_cast</em> and <em>reinterpret_cast</em><br>\n  In C++ Programming Language, 3rd ed, Bjarne Stroustrup describes it on page 130. There's a whole section on this in Chapter 6.<br>\n  You can recast your Parent class to Child class. This requires you to know when each one is which. In the book, Dr. Stroustrup talks about different techniques to avoid this situation.</p>\n</blockquote>\n\n<p>Do not do this.  This negates the polymorphism that you're trying to achieve in the first place!</p>\n"}, {'answer_id': 41103, 'author': 'Adam Hollidge', 'author_id': 4069, 'author_profile': 'https://Stackoverflow.com/users/4069', 'pm_score': 3, 'selected': False, 'text': '<p>You might also consider <a href="http://www.boost.org/doc/libs/1_36_0/doc/html/any.html" rel="noreferrer">boost::any</a>. I\'ve used it for heterogeneous containers. When reading the value back, you need to perform an any_cast. It will throw a bad_any_cast if it fails. If that happens, you can catch and move on to the next type.</p>\n\n<p>I <em>believe</em> it will throw a bad_any_cast if you try to any_cast a derived class to its base. I tried it:</p>\n\n<blockquote>\n<pre><code>  // But you sort of can do it with boost::any.\n\n  vector&lt;any&gt; valueVec;\n\n  valueVec.push_back(any(Parent()));\n  valueVec.push_back(any(Child()));        // remains a Child, wrapped in an Any.\n\n  Parent p = any_cast&lt;Parent&gt;(valueVec[0]);\n  Child c = any_cast&lt;Child&gt;(valueVec[1]);\n  p.write();\n  c.write();\n\n  // Output:\n  //\n  // Parent: 1\n  // Child: 2, 2\n\n  // Now try casting the child as a parent.\n  try {\n      Parent p2 = any_cast&lt;Parent&gt;(valueVec[1]);\n      p2.write();\n  }\n  catch (const boost::bad_any_cast &amp;e)\n  {\n      cout &lt;&lt; e.what() &lt;&lt; endl;\n  }\n\n  // Output:\n  // boost::bad_any_cast: failed conversion using boost::any_cast\n</code></pre>\n</blockquote>\n\n<p>All that being said, I would also go the shared_ptr route first! Just thought this might be of some interest.</p>\n'}, {'answer_id': 41106, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 2, 'selected': False, 'text': "<p>Most container types want to abstract the particular storage strategy, be it linked list, vector, tree-based or what have you.  For this reason, you're going to have trouble with both possessing and consuming the aforementioned cake (i.e., the cake is lie (NB:  someone had to make this joke)).</p>\n\n<p>So what to do?  Well there are a few cute options, but most will reduce to variants on one of a few themes or combinations of them:  picking or inventing a suitable smart pointer, playing with templates or template templates in some clever way, using a common interface for containees that provides a hook for implementing per-containee double-dispatch.</p>\n\n<p>There's basic tension between your two stated goals, so you should decide what you want, then try to design something that gets you basically what you want.  It <em>is</em> possible to do some nice and unexpected tricks to get pointers to look like values with clever enough reference counting and clever enough implementations of a factory.  The basic idea is to use reference counting and copy-on-demand and constness and (for the factor) a combination of the preprocessor, templates, and C++'s static initialization rules to get something that is as smart as possible about automating pointer conversions.</p>\n\n<p>I have, in the past, spent some time trying to envision how to use Virtual Proxy / Envelope-Letter / that cute trick with reference counted pointers to accomplish something like a basis for value semantic programming in C++.</p>\n\n<p>And I think it could be done, but you'd have to provide a fairly closed, C#-managed-code-like world within C++ (though one from which you could break through to underlying C++ when needed).  So I have a lot of sympathy for your line of thought.</p>\n"}, {'answer_id': 41287, 'author': 'Serge', 'author_id': 1007, 'author_profile': 'https://Stackoverflow.com/users/1007', 'pm_score': 2, 'selected': False, 'text': '<p>Just to add one thing to all <a href="https://stackoverflow.com/questions/41045/can-i-have-polymorphic-containers-with-value-semantics-in-c#41059">1800 INFORMATION</a> already said.</p>\n\n<p>You might want to take a look at <a href="https://rads.stackoverflow.com/amzn/click/com/020163371X" rel="nofollow noreferrer" rel="nofollow noreferrer">"More Effective C++"</a> by Scott Mayers "Item 3:  Never treat arrays polymorphically" in order to better understand this issue.</p>\n'}, {'answer_id': 44855, 'author': 'ben', 'author_id': 4607, 'author_profile': 'https://Stackoverflow.com/users/4607', 'pm_score': 3, 'selected': False, 'text': '<p>Yes, you can.</p>\n\n<p>The boost.ptr_container library provides polymorphic value semantic versions of the standard containers. You only have to pass in a pointer to a heap-allocated object, and the container will take ownership and all further operations will provide value semantics , except for reclaiming ownership, which gives you almost all the benefits of value semantics by using a smart pointer.</p>\n'}, {'answer_id': 71264, 'author': '0124816', 'author_id': 11521, 'author_profile': 'https://Stackoverflow.com/users/11521', 'pm_score': 4, 'selected': False, 'text': "<p>I just wanted to point out that vector&lt;Foo&gt; is usually more efficient than vector&lt;Foo*&gt;. In a vector&lt;Foo&gt;, all the Foos will be adjacent to each other in memory. Assuming a cold TLB and cache, the first read will add the page to the TLB and pull a chunk of the vector into the L# caches; subsequent reads will use the warm cache and loaded TLB, with occasional cache misses and less frequent TLB faults.</p>\n\n<p>Contrast this with a vector&lt;Foo*&gt;: As you fill the vector, you obtain Foo*'s from your memory allocator. Assuming your allocator is not extremely smart, (tcmalloc?) or you fill the vector slowly over time, the location of each Foo is likely to be far apart from the other Foos: maybe just by hundreds of bytes, maybe megabytes apart.</p>\n\n<p>In the worst case, as you scan through a vector&lt;Foo*&gt; and dereferencing each pointer you will incur a TLB fault and cache miss -- this will end up being a <em>lot</em> slower than if you had a vector&lt;Foo&gt;. (Well, in the really worst case, each Foo has been paged out to disk, and every read incurs a disk seek() and read() to move the page back into RAM.)</p>\n\n<p>So, keep on using vector&lt;Foo&gt; whenever appropriate. :-)</p>\n"}, {'answer_id': 71355, 'author': 'Johann Gerell', 'author_id': 6345, 'author_profile': 'https://Stackoverflow.com/users/6345', 'pm_score': 1, 'selected': False, 'text': "<p>I'm using my own templated collection class with exposed value type semantics, but internally it stores pointers. It's using a custom iterator class that when dereferenced gets a value reference instead of a pointer. Copying the collection makes deep item copies, instead of duplicated pointers, and this is where most overhead lies (a really minor issue, considered what I get instead).</p>\n\n<p>That's an idea that could suit your needs.</p>\n"}, {'answer_id': 49720854, 'author': 'dragly', 'author_id': 632150, 'author_profile': 'https://Stackoverflow.com/users/632150', 'pm_score': 3, 'selected': False, 'text': '<p>While searching for an answer to this problem, I came across both this and <a href="https://stackoverflow.com/questions/18856824/ad-hoc-polymorphism-and-heterogeneous-containers-with-value-semantics">a similar question</a>. In the answers to the other question you will find two suggested solutions:</p>\n\n<ol>\n<li>Use std::optional or boost::optional and a visitor pattern. This solution makes it hard to add new types, but easy to add new functionality. </li>\n<li>Use a wrapper class similar to what <a href="https://www.youtube.com/watch?v=QGcVXgEVMJg" rel="noreferrer">Sean Parent presents in his talk</a>. This solution makes it hard to add new functionality, but easy to add new types.</li>\n</ol>\n\n<p>The wrapper defines the interface you need for your classes and holds a pointer to one such object. The implementation of the interface is done with free functions.</p>\n\n<p>Here is an example implementation of this pattern:</p>\n\n<pre><code>class Shape\n{\npublic:\n    template&lt;typename T&gt;\n    Shape(T t)\n        : container(std::make_shared&lt;Model&lt;T&gt;&gt;(std::move(t)))\n    {}\n\n    friend void draw(const Shape &amp;shape)\n    {\n        shape.container-&gt;drawImpl();\n    }\n    // add more functions similar to draw() here if you wish\n    // remember also to add a wrapper in the Concept and Model below\n\nprivate:\n    struct Concept\n    {\n        virtual ~Concept() = default;\n        virtual void drawImpl() const = 0;\n    };\n\n    template&lt;typename T&gt;\n    struct Model : public Concept\n    {\n        Model(T x) : m_data(move(x)) { }\n        void drawImpl() const override\n        {\n            draw(m_data);\n        }\n        T m_data;\n    };\n\n    std::shared_ptr&lt;const Concept&gt; container;\n};\n</code></pre>\n\n<p>Different shapes are then implemented as regular structs/classes. You are free to choose if you want to use member functions or free functions (but you will have to update the above implementation to use member functions). I prefer free functions:</p>\n\n<pre><code>struct Circle\n{\n    const double radius = 4.0;\n};\n\nstruct Rectangle\n{\n    const double width = 2.0;\n    const double height = 3.0;\n};\n\nvoid draw(const Circle &amp;circle)\n{\n    cout &lt;&lt; "Drew circle with radius " &lt;&lt; circle.radius &lt;&lt; endl;\n}\n\nvoid draw(const Rectangle &amp;rectangle)\n{\n    cout &lt;&lt; "Drew rectangle with width " &lt;&lt; rectangle.width &lt;&lt; endl;\n}\n</code></pre>\n\n<p>You can now add both <code>Circle</code> and <code>Rectangle</code> objects to the same <code>std::vector&lt;Shape&gt;</code>:</p>\n\n<pre><code>int main() {\n    std::vector&lt;Shape&gt; shapes;\n    shapes.emplace_back(Circle());\n    shapes.emplace_back(Rectangle());\n    for (const auto &amp;shape : shapes) {\n        draw(shape);\n    }\n    return 0;\n}\n</code></pre>\n\n<p>The downside of this pattern is that it requires a large amount of boilerplate in the interface, since each function needs to be defined three times.\nThe upside is that you get copy-semantics:</p>\n\n<pre><code>int main() {\n    Shape a = Circle();\n    Shape b = Rectangle();\n    b = a;\n    draw(a);\n    draw(b);\n    return 0;\n}\n</code></pre>\n\n<p>This produces:</p>\n\n<pre><code>Drew rectangle with width 2\nDrew rectangle with width 2\n</code></pre>\n\n<p>If you are concerned about the <code>shared_ptr</code>, you can replace it with a <code>unique_ptr</code>.\nHowever, it will no longer be copyable and you will have to either move all objects or implement copying manually.\nSean Parent discusses this in detail in his talk and an implementation is shown in the above mentioned answer.</p>\n'}]
['https://Stackoverflow.com/questions/41045', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2994/']