Question

I'm coming back to c++ from a long absence, and am picking up c++11 and boost::asio at the same time.

After GotW #93 and #94, I'm naturally fired up about using auto.

Imagine my disapointment when this doesn't compile:

auto io = boost::asio::io_service{};

but I must use this instead:

boost::asio::io_service io{};

Why does the second compile, but the first not? The error I'm getting is

Call to implicitly-deleted copy constructor of 'boost::asio::io_service'

boost::asio::deadline::timer exhibits the same behavior, but boost::posix_time::seconds does not.

(I'm using xcode + clang + boost 1_55_0).

Full compiling example, modified from the boost asio tutorial:

#include <iostream>
#include <memory>
#include <boost/asio.hpp>
#include <boost/date_time/posix_time/posix_time.hpp>

namespace asio = boost::asio;

int main(int argc, const char * argv[]) {
    using error_code = const boost::system::error_code;

    asio::io_service io{};
    asio::deadline_timer t{io, boost::posix_time::seconds{2}};

    int count = 0;
    std::function<void (const error_code&)> fn = [&](const error_code& e) {
        if (count < 5) {
            std::cout << "Hello World" << std::endl;
            ++(count);
            t.expires_at(t.expires_at() + boost::posix_time::seconds{1});
            t.async_wait(fn);
        }
    };
    t.async_wait(fn);

    io.run();

    std::cout << "Final count is " << count << std::endl;

    return 0;
}
Was it helpful?

Solution 2

The error is pretty self-explanatory, it has nothing to do with the use of auto. The following code will produce a similar error message:

struct foo
{
    foo() = default;
    foo(foo const&) = delete;
};

foo f = foo{};

The last line above requires an accessible copy-constructor (even if the compiler elides the copy).

boost::asio::io_service's copy-constructor is implicitly deleted, probably due to the presence of one or more non-copyable data members or base classes. You already have the right solution to fix the error:

asio::io_service io{};

OTHER TIPS

The class asio::io_service derives from noncopyable, which means the copy constructor has been intentionally made inaccessible. This statement won't work for the same reason:

boost::asio::io_service io = boost::asio::io_service{};

In this instance, the problem is not because of the auto keyword, but lack of access to the required constructor. The tutorial code uses the normal constructor, which is public, and so compiles fine.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top