kro*_*jew 1 c++ stl visual-studio-2012
我尝试用普通的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);
一切都很好.为什么第二部分失败了?为了增加这种情况的陌生感,当试图按值返回List时:
typedef std::list<int, std::allocator<int>> TempType;
TempType func()
{
    TempType theList(std::allocator<int>());
    return theList;
}
我得到"错误C2664:'std :: list <_Ty,_Alloc> :: list(const std :: list <_Ty,Alloc>&)':无法从'TempType( _cdecl*)转换参数1(std :: allocator) < Ty>( _ cdecl*)(void))'to'const std :: list <_Ty,_Alloc>&'".看起来编译器将列表视为函数声明.知道为什么会这样吗?
你遇到了最令人烦恼的解析.编译器正在解析theList(std::allocator<int>())函数声明的定义.这应该会解决你的问题:
std::allocator<int> alloc;
std::list<int, std::allocator> > theList(alloc);
| 归档时间: | 
 | 
| 查看次数: | 971 次 | 
| 最近记录: |