最新消息:Welcome to the puzzle paradise for programmers! Here, a well-designed puzzle awaits you. From code logic puzzles to algorithmic challenges, each level is closely centered on the programmer's expertise and skills. Whether you're a novice programmer or an experienced tech guru, you'll find your own challenges on this site. In the process of solving puzzles, you can not only exercise your thinking skills, but also deepen your understanding and application of programming knowledge. Come to start this puzzle journey full of wisdom and challenges, with many programmers to compete with each other and show your programming wisdom! Translated with DeepL.com (free version)

mutex - Why does the unique_pointer solve the "no matching function for call to 'construct_at'&quot

matteradmin5PV0评论

I have a class with a mutex in it:

Class StoreNumbers{
  StoreNumbers();
  AddNumber(size_t number){
    const std::lock_guard<std::mutex> lock(lock_);
    numbers_.push_back(number);
  }

  private:
  std::mutex lock_;
  std::vector<size_t> numbers_;

};

The purpose of the class is to be able to store numbers while used in a multithreaded context. There is certainly better ways to do that but that illustrates my question.

Now I want to have various objects of these classes, in order to store different types of numbers. I also want each of these types to have a different mutex, since they are unrelated.

If I write:

std::vector<StoreNumbers> vec;
vec.push_back(StoreNumber());

I get the compiler error: no matching function for call to 'construct_at', which I understand since the mutex is non copyable.

If instead I use:

std::unique_ptr<std::mutex> lock_=std::make_unique<std::mutex>();

for the lock and dereference it for the lock_guard, I do not get the error anymore. I do not understand why. Thanks for the help!

Articles related to this article

Post a comment

comment list (0)

  1. No comments so far