Search code examples
c++c++11boostmove-semanticsboost-pool

Move constructor is not called when using boost::pool_allocator


I have the following simple test code.

#include <stack>
#include <iostream>
#include "boost/pool/pool_alloc.hpp"

struct Frame
{
    uint32_t i{};

    Frame(uint32_t _i) : i(_i) {}

    Frame(const Frame& f)
    {
        std::cout << "Copy constructor" << std::endl;
        i = f.i;
    }

    Frame(Frame&& f)
    {
        std::cout << "Move constructor" << std::endl;
        std::swap(i, f.i);
    }
};

int main(int argc, char* argv[])
{
    {
        std::stack<Frame, std::deque<Frame>> stack;

        Frame f(0);
        stack.push(std::move(f)); // Move constructor
        stack.push(Frame(1)); // Move constructor
    }

    {
        std::stack<Frame, std::deque<Frame, boost::pool_allocator<Frame>>> stack;

        Frame f(0);
        stack.push(std::move(f)); // Copy constructor
        stack.push(Frame(1)); // Copy constructor
    }


    return 0;
}

When I compile this code with either Clang or GCC, it gives me the following output:

Move constructor
Move constructor
Copy constructor
Copy constructor

Why does using boost::pool_allocator prevent the compiler from using the move constructor?
Am I missing something?


Solution

  • pool_allocator does not perfect forward the arguments to construct: It simply takes a const reference to the value type and passes that on as the initializer for placement new.

    That is because pool_allocator has not been updated for C++11 yet.