Vega4
Vega4

Reputation: 989

Adding class cotaining std::thread to a vector

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

Answers (2)

user8063157
user8063157

Reputation: 285

You can also try

v.push_back(std::move(*a));

Upvotes: 0

xaxxon
xaxxon

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

Related Questions