我有一个微不足道的分配器:C++:哪些构造函数在向量中调用<int> vn {MyAllocator <int>(a)}?
// alloc.h
#include <cstdlib>
#include <new>
#include <iostream>
template <class T>
struct Mallocator {
typedef T value_type;
Mallocator() {
std::cout << "default ctor is called" << std::endl;
}
template <class U> Mallocator(const Mallocator<U>&) {
std::cout << "copy ctor is called" << std::endl;
}
T* allocate(std::size_t n) {
std::cout << "Mallocator::allocate(size_t n) is called, n = " << n << " ";
if(n > std::size_t(-1)/sizeof(T)) throw std::bad_alloc();
if(T *p = static_cast<T*>(std::malloc(n*sizeof(T)))) {
std::cout << "return p = " << std::hex << (uintptr_t)p << std::dec << std::endl;
return p;
}
throw std::bad_alloc();
}
void deallocate(T* p, std::size_t n) {
std::cout << "Mallocator::deallocate(T *p, size_t n) is called, p = " << std::hex << (uintptr_t)p << std::dec << " n = " << n << std::endl;
std::free(p);
}
};
template <class T, class U>
bool operator==(const Mallocator<T>&, const Mallocator<U>&) { return true; }
template <class T, class U>
bool operator!=(const Mallocator<T>&, const Mallocator<U>&) { return false; }
这是客户机代码(只有一个的A
,B
,C
使用):
#include "alloc.h"
#include <vector>
#include <iostream>
using namespace std;
int main() {
Mallocator<int> a;
cout << "---instantiate---" << endl;
// vector<int, Mallocator<int>> v(a); // A
vector<int, Mallocator<int>> v{Mallocator<int>(a)}; // B
// vector<int, Mallocator<int>> v(Mallocator<int>(a)); // C
cout << "---push_back(1)---" << endl;
v.push_back(1);
cout << "---push_back(2)---" << endl;
v.push_back(2);
cout << "---push_back(3)---" << endl;
v.push_back(3);
cout << "---push_back(4)---" << endl;
v.push_back(4);
cout << "---push_back(5)---" << endl;
v.push_back(5);
cout << "---exiting---" << endl;
}
输出,不管A
或B
是总是这样:
default ctor is called
---instantiate---
---push_back(1)---
// omitted for brevity..
我的问题:
(1)如果A
存在,分配器只构造一次,这是可以理解的。但是,当存在B
而不是A
时,显然Mallocator
的复制构造函数在B
中调用,但输出并未反映此情况。为什么?
(2)如果B
存在,哪个构造函数std::vector
被调用?在这个reference中,唯一带有初始化列表的构造函数看起来不像这样。如果我用C
而不是B
,它不会编译,铛++的错误信息是没有帮助..
Eidt:我知道这个分配器是微不足道,但它不是这个问题的要点..
“alloc.h”的代码是从页面末尾的here改编而来的。
是的,没错,虽然修复了这个代码(从U中移除模板),但它仍然不会调用复制构造函数的副作用。或者,更好的说,_maybe_不会打电话。 – Swift
@Swift你会看到vector的参数至少有一个拷贝到它存储的分配器。这不是可以消除的。 –
这是不容置疑的。实际上,我看到两个好奇的(8)并不是在这种情况下可以调用的正确构造函数。 – Swift