【发布时间】:2017-06-22 16:06:20
【问题描述】:
我正在尝试为向量编写自定义分配器。这是到目前为止的骨架代码:
#include <iostream>
#include <vector>
struct Noisy
{
Noisy() { std::cout << "Default ctor called" << '\n'; }
Noisy(const Noisy&) { std::cout << "Copy ctor called" << '\n'; }
Noisy& operator=(const Noisy&) { std::cout << "Copy assignment called" << '\n'; return *this; }
Noisy(Noisy&&) { std::cout << "Move ctor called" << '\n'; }
Noisy& operator=(Noisy&&) { std::cout << "Move assignment called" << '\n'; return *this; }
};
template <typename T>
struct StackAllocator : Noisy
{
using value_type = T;
T* allocate(std::size_t n) { return nullptr; }
void deallocate(T* p, std::size_t n) { }
};
int main()
{
using alloc_t = StackAllocator<int>;
auto alloc = alloc_t{};
std::vector<int, alloc_t> vec(alloc);
}
在 gcc 6.3 上,这会产生我所期望的结果:(Online link)
Default ctor called
Copy ctor called
但是,在 clang 3.9 上,这会产生:(Online link)
Default ctor called
Copy ctor called
Move ctor called
Move ctor called
这是clang向量实现的源码。 (here),但我找不到任何可以解释这两个额外移动结构的东西。 (有趣的是我发现它使用压缩对来利用 EBO 的空分配器)
【问题讨论】:
标签: c++ c++11 gcc clang++ allocator