【问题标题】:Failure while trying to construct a std::list with an allocator尝试使用分配器构造 std::list 时失败
【发布时间】: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&lt;int, std::allocator&lt;int&gt;&gt; 实际上写成std::list&lt;int, std::allocator&lt;int&gt; &gt;? (我没有深入研究;对分配器不是很有经验)
  • @Dave:既不需要也不相关。
  • @Dave:我有“不同的行为”,因为我使用的编译器尽可能地支持 /current/ C++ 标准。

标签: c++ visual-studio-2012 stl


【解决方案1】:

您遇到了the most vexing parse。编译器将theList(std::allocator&lt;int&gt;()) 的定义解析为函数声明。这应该可以解决您的问题:

std::allocator<int> alloc;
std::list<int, std::allocator> > theList(alloc);

【讨论】:

  • @GManNickG - std::list 没有采用右值引用的构造函数,因此传递move(alloc) 将调用左值构造函数,因此没有区别。
  • @PeteBecker:你说得对,我的错。一开始我有点惊讶,但这是有道理的,因为分配器几乎肯定会是rebinded。
【解决方案2】:

它被称为the most vexing parse

你不小心声明了一个函数。添加一组额外的括号将使其明确。

std::list<int, std::allocator<int>> theList((std::allocator<int>()));
//                                          ^                     ^

【讨论】:

  • 但是,为什么不去获取该类型的构造函数呢?我的意思是,int i(0) 等于 int i = 0
  • @Infested:注意 int(0) 和 int() 的不同之处,现在输入一个名称,你就有了“int f()”,它是......好吧,它是什么?跨度>
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-05-04
  • 2015-01-14
  • 2015-09-26
  • 1970-01-01
相关资源
最近更新 更多