Reputation: 989
Class declaration:
class cA{
private:
std::thread t;
public:
cA()=default;
};
Somehere in another source file:
cA *a = new cA();
std::vector<cA> v;
v.push_back(*a);
This results in the following error at compile time:
C2280: cA::cA(const cA &)': attempting to reference a deleted function
I think it might have something to do with the fact that std::thread
is missing a copy constructor and that the vector tries to make a copy of the cA
object. Would anyone be willing to explain?
Upvotes: 2
Views: 343
Reputation: 19801
std::thread
is not copyable, so the compiler can not generate a default copy constructor because it doesn't know what to do with the uncopyable type in the class. What would it put in the std::thread
variable in the new copy?
Because it cannot generate the copy constructor, it is deleted, the same as if you had said
cA(const cA &) = delete;
in your class definition.
Here are the rules for when it can and cannot create an implicit copy constructor:
http://en.cppreference.com/w/cpp/language/copy_constructor
The line relevant to your situation is:
T
has non-static data members that cannot be copied (have deleted, inaccessible, or ambiguous copy constructors);
Also, as a comment on your question points out, your actual code, even if it did compile, isn't good. It will leak a cA
object. The correct code here (fixed per comment):
v.emplace_back(); // since the cA constructor takes no parameters
or
v.push_back(cA());
Neither of these require cA
to be copyable because its move constructor is used.
Upvotes: 2