Below is the minimalist problem of the code:
struct B {
B () = default;
//~B () {}; // error: use of deleted function ‘B& B::operator=(const B&)’
std::unique_ptr<int> m_pB = nullptr;
};
int main ()
{
std::vector<B> vB;
vB.erase(vB.begin());
}
Above code compiles fine, unless the destructor is uncommented. For my requirement, I need to have a body of ~B()
explicitly defined.
How can I define the body of destructor with the unique_ptr
co-existing in the same class?
Note: Tried defining = default
versions of copy & move constructor to no avail. In my real code, unique_ptr<int>
is unique_ptr<forward_declared_class>
. Couldn't locate this problem in SO, though I am sure it must be present. Feel free to mark as dupe.
Seems like your code requires B
to be copy constructible and copy assignable for std::vector
(at least for visual c++, which I tested).
Copy constructor and copy assignement operators can only be = delete
because of std::unique_ptr
(implementations declared = default
should cause the function to be deleted as well), and, by implementing destructor, you disable default implementations of move constructor and move assignment operator.
So you need to explicitly declare the move assignment operator. Try:
#include <memory>
#include <vector>
struct B {
B () = default;
~B () {}
B& operator=(B&&) = default;
std::unique_ptr<int> m_pB = nullptr;
};
int main ()
{
std::vector<B> vB;
vB.erase(vB.begin());
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With