How can I insert into vector with a class including condition variable?

Viewed 122

I try to insert into vector with a class including condition variable,my code as follow:

class LockRequest {
   public:
    LockRequest( ) : granted_(false) {}
    bool granted_;
  };

  class LockRequestQueue {
   public:
    std::list<LockRequest> request_queue_;
    std::condition_variable cv_;  // for notifying blocked transactions on this rid
    bool upgrading_ = false;
  };

int main(){
    LockRequestQueue request;
    std::vector<LockRequestQueue> vecs;
    vecs.push_back(request);
    return 0;
}

but I get error.When I remove the condition variable cv_,the result is correct.How can I fix this problem??

1 Answers

std::condition_variable is not

  • copy constructible,
  • move constructible,
  • copy assignable or
  • move assignable.

So adding it directly to any class as a member would also add those qualifications to that class too.
In order to avoid that, we use an extra level of indirection, for example, a std::unique_ptr to hold a pointer to it.

class LockRequestQueue {
public:

    LockRequestQueue() // make a condition variable and assign it to the unique_ptr
        :cv_(std::make_unique<std::condition_variable>())
    {}

    std::list<LockRequest> request_queue_;
    std::unique_ptr<std::condition_variable> cv_;  //notice the unique_ptr
    bool upgrading_ = false;
};

And now, in our main() function, we use std::move to push to the vector since std::unique_ptr itself is not copy constructible:

int main()
{

    LockRequestQueue request;
    std::vector<LockRequestQueue> vecs;
    vecs.push_back(std::move(request)); //notice the std::move
    return 0;
}
Related