0

My program has a class similar to the following:

class IOWorker {
    
    std::thread                                    thread_;
    boost::asio::io_service                        ios_;
    boost::optional<boost::asio::io_service::work> work_;
    Callback                                       callback_;
    
    static thread_local IOWorker*                  this_thread_worker_;
    
public:
    IOWorker(Callback cb);
    ~IOWorker();
        
    // IO worker threads will call this to fetch their instance
    static IOWorker* getIOWorkerInstance (void) {
        return this_thread_worker_;
    }
};
    
IOWorker::IOWorker (Callback cb) : callback_{std::move(cb)}
{
    work_ = boost::in_place(boost::ref(ios_));
    thread_ = std::thread{[this] () {
        this_thread_worker_ = this;
        ios_.run();
    }};
}

Main thread calls the following function to create IOWorker instances/threads:

std::vector<IOWorker> startIOWorkers(Callback cb)
{
    std::vector<IOWorker> launched_workers;
    launched_workers.reserve(10);
        
    for (int i = 0; i < 10; ++i) {
        launched_workers.emplace_back(cb);
    }
    
    return launched_workers;
}

But the compilation fails with the following error (pointing to _Up):

error: call to implicitly-deleted copy constructor of 'IOWorker'
::new((void*)__p) _Up(_VSTD::forward<_Args>(__args)...);

Not sure what changes I need to make in the above class to resolve this error.

I want this class (objects) to be non-copyable, but can be movable.

Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
void
  • 338
  • 5
  • 19
  • 1
    The user-declared destructor means that the implicitly-declared [move constructor](https://en.cppreference.com/w/cpp/language/move_constructor) will not be created for your class. If all those members are move-constructible, you could write a move constructor by adding `IOWorker(IOWorker&&) = default;` to the class definition. – Nathan Pierson Aug 04 '21 at 23:07
  • 2
    It would help you and people on this site if you minimized your example. I am sure you can reproduce the error without thread+network+... – Marc Glisse Aug 04 '21 at 23:09
  • The other answer is correct, your class is not copyable and`std::vector` doesn't work because in this context because of that. However this doesn't mean that you should make your class copyable at all cost, maybe it simply means that you cannot not store de instances in a vector. Maybe a static array (std::array) or a list (std::list) is good enough for storing many of these instances. – alfC Aug 06 '21 at 01:44

0 Answers0