Skip to main content
Fanael's random ruminations

Archives for topic i-hate-c++

How to: accidentally break empty base optimization

Published on the

Topics: i-hate-c++

A reasonably common idiom in C++ code is the use of the following or similar class to inhibit move and copy operations, to avoid having to repeat the four deleted functions in every class:

C++
class noncopyable {
public:
    noncopyable(const noncopyable&) = delete;
    noncopyable(noncopyable&&) = delete;
    noncopyable& operator=(const noncopyable&) = delete;
    noncopyable& operator=(noncopyable&&) = delete;
protected:
    noncopyable() = default;
    ~noncopyable() = default;
};

I'm personally not a huge fan of the noncopyable name, because it describes how instead of why, but that's neither here nor there.

The noncopyable class can be mixed in using inheritance, like so:

C++
class foo : private noncopyable {
    // …
};

So far, so good, but there's more to it than meets the eye.

Read the full article…