Search code examples
c++c++11shared-ptrcondition-variable

Issues when creating a shared pointer of condition variable


I apologize if this has been asked before, I was not able to find it online. Why does the compiler think that I am trying to call the copy constructor of std::condition_variable?

#include <iostream>
#include <utility>
#include <vector>
#include <memory>
#include <condition_variable>
using namespace std;

class A {
 public:
  A() = default;
  A(A&&) = default;
  A& operator=(A&&) = default;
  A(const A&) = delete;
  A& operator=(const A&) = delete;
};
int main() {

  std::vector<std::shared_ptr<std::condition_variable>> m;
  m.push_back(std::make_shared<std::condition_variable>(std::condition_variable{}));

  // no complains here
  std::vector<std::shared_ptr<A>> m_a;
  m_a.push_back(std::make_shared<A>(A{}));

  return 0;
}

The error I get is that I am trying to use the deleted copy constructor of std::condition_variable.. I guess what I am trying to ask is why the move constructor is not called with that invocation of make_shared


Solution

  • In

    std::make_shared<std::condition_variable>(std::condition_variable{})
    

    std::condition_variable{} creates a std::condition_variable. This means that std::make_shared is going to construct it's internal std::condition_variable with the passed parameter which invokes the copy constructor. If you need a default constructed std::condition_variable then you can use

    std::make_shared<std::condition_variable>()