The problem only appears when adding the ~MyClass()
function. I think the error is undefined behaviour or has something to do with the const MyClass&
maybe this kind reference doesn't work with emplace_back
.
Comments explain the rest:
#include <vector>
#include <iostream>
#include <memory>
struct MyClass
{
const int x;
MyClass(int _x) : x(_x)
{
}
};
struct MyClass2
{
std::unique_ptr<MyClass> my;
MyClass2(const MyClass& my2)
{
my.reset(new MyClass(my2.x));
}
// when adding this function
// error: static assertion failed: result type must be constructible from input type
~MyClass2()
{
printf("deleting\n");
}
};
int main()
{
MyClass main(12);
std::vector<MyClass2> ts;
for (int i = 0; i < 10; ++i)
{
ts.emplace_back(main);
}
printf("%i\n", ts[0].my->x);
return 0;
}