【发布时间】:2013-04-17 19:29:09
【问题描述】:
我在尝试使用带有自定义分配器的普通 std::list 编译一些代码时发现了一个奇怪的行为。考虑以下代码:
std::list<int, std::allocator<int>> theList;
theList.push_back(1);
这是一个添加了一些数据的普通列表变量。现在,如果我将其切换为:
std::list<int, std::allocator<int>> theList(std::allocator<int>());
theList.push_back(1);
Visual Studio 2012 编译失败,出现“错误 C2228:'.push_back' 左侧必须有类/结构/联合”。当然 std::list 有一个构造函数,它接受对分配器的 const 引用。但是,如果我将其更改为:
std::list<int, std::allocator<int>> theList = std::list<int, std::allocator<int>>(std::allocator<int>());
theList.push_back(1);
一切都很好。为什么第二部分失败了?更奇怪的是,当尝试按值返回列表时:
typedef std::list<int, std::allocator<int>> TempType;
TempType func()
{
TempType theList(std::allocator<int>());
return theList;
}
我收到“错误 C2664:'std::list<_ty>::list(const std::list<_ty>Alloc> &)':无法从 'TempType ( em>_cdecl *)(std::allocatorTy> (_cdecl *)(void))' 到 'const std::list<_ty> &'”。看起来编译器将列表视为函数声明。知道为什么会这样吗?
【问题讨论】:
-
列表不应该是一个 T,而不是两个?
-
@Infested std::list 可以将分配器作为第二种类型
-
我假设在你的真实代码中,
std::list<int, std::allocator<int>>实际上写成std::list<int, std::allocator<int> >? (我没有深入研究;对分配器不是很有经验) -
@Dave:既不需要也不相关。
-
@Dave:我有“不同的行为”,因为我使用的编译器尽可能地支持 /current/ C++ 标准。
标签: c++ visual-studio-2012 stl