Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 762
Matteo Bertello Avatar asked Nov 24 '25 07:11

Matteo Bertello


1 Answers

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.

like image 79
Columbo Avatar answered Nov 25 '25 21:11

Columbo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!