Note that there are some explanatory texts on larger screens.

plurals
  1. POHandling smart pointers in stl container
    primarykey
    data
    text
    <p>I've a class <code>Foo&lt;T&gt;</code> which has a vector of smart pointers to <code>Shape</code> derived classes. I'm trying to implement an <code>at(index)</code> member function. Here's what I would to do intuitively: </p> <pre><code>Foo&lt;float&gt; myfoo; std::unique_ptr&lt;Shape&lt;float&gt;&gt; shape_ptr = myfoo.at(i); shape_ptr-&gt;doSomething(param1, param2, ...); </code></pre> <p>When defining the <code>at(index)</code> function, I'm getting a compiler error message. Note that the move constructor was defined and that the Shape base class is abstract. Below, I'm giving some code for illustration purposes.</p> <p>Furthermore, I found recently on the web an example on how to overload the assignment operator using <code>std::move</code>. I usually follow the Copy-Swap idiom. Which of those two ways for overloading the mentioned operator makes sense for my case? Below, I'm also illustrating the function's definition.</p> <pre><code>template &lt; typename T &gt; class Foo{ public: Foo(); Foo( Foo &amp;&amp; ); ~Foo(); void swap(Foo&lt;T&gt; &amp;); //Foo&lt;T&gt; &amp; operator =( Foo&lt;T&gt; ); Foo&lt;T&gt; &amp; operator =( Foo&lt;T&gt; &amp;&amp; ); std::unique_ptr&lt;Shape&lt;T&gt; &gt; at ( int ) const; // error here! int size() const; private: std::vector&lt; std::unique_ptr&lt;Shape&lt;T&gt; &gt; &gt; m_Bank; }; template &lt; typename T &gt; Foo&lt;T&gt;::Foo( Foo &amp;&amp; other) :m_Bank(std::move(other.m_Bank)) { } /*template &lt; typename T &gt; void Filterbank&lt;T&gt;::swap(Filterbank&lt;T&gt; &amp; refBank ){ using std::swap; swap(m_Bank, refBank.m_Bank); } template &lt; typename T &gt; Foo&lt;T&gt; &amp; Filterbank&lt;T&gt;::operator =( Foo&lt;T&gt; bank ){ bank.swap(*this); return (*this); }*/ template &lt; typename T &gt; Foo&lt;T&gt; &amp; Foo&lt;T&gt;::operator =( Foo&lt;T&gt; &amp;&amp; bank ){ //bank.swap(*this); m_Bank = std::move(bank.m_Bank); return (*this); } template &lt; typename T &gt; std::unique_ptr&lt;Shape&lt;T&gt; &gt; Foo&lt;T&gt;::at( int index ) const{ return m_Bank[index]; // Error here! =&gt; error C2248: 'std::unique_ptr&lt;_Ty&gt;::unique_ptr' : cannot access private member declared in class 'std::unique_ptr&lt;_Ty&gt;' } </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload