c++ - 使用 new 表达式的非静态数据成员初始化

标签 c++ c++11 gcc language-lawyer

考虑以下代码:

#include <map>

template <typename T>
struct X {
    std::map<int, T>* storage = new std::map<int, T>();
};

int main() {
    X<int> x;
}

编译于 clang 3.6.0 , 但无法在 gcc 5.1 上编译.但是,如果 storage 的类型,它会编译。相反 std::vector<T>* (或者只是 T* )。

我相当确定这是 gcc 方面的编译器错误(编辑:我将其作为 66344 提交),但我想我会要求确定:上面的示例是否有任何理由应该' t 编译?

gcc 编译错误:

main.cpp:5:51: error: expected ';' at end of member declaration    
     std::map<int, T>* storage = new std::map<int, T>();    
                                                   ^    

main.cpp:5:51: error: declaration of 'std::map<int, T> X<T>::T'    
main.cpp:3:11: error:  shadows template parm 'class T'    
 template <typename T>    
           ^

main.cpp:5:52: error: expected unqualified-id before '>' token    
     std::map<int, T>* storage = new std::map<int, T>();    
                                                    ^    
main.cpp:5:46: error: wrong number of template arguments (1, should be at least 2)    
     std::map<int, T>* storage = new std::map<int, T>();    
                                              ^

In file included from /usr/local/include/c++/5.1.0/map:61:0,    
                 from main.cpp:1:    
/usr/local/include/c++/5.1.0/bits/stl_map.h:96:11: note: provided for 'template<class _Key, class _Tp, class _Compare, class _Alloc> class std::map'    
     class map    
           ^

最佳答案

这是 Core issue 325 中描述的问题的另一个示例(请参阅“2011 年 8 月 session 的笔记”,其中有一个非常相似的示例),即当编译器尝试确定表达式的结尾位置时,模板参数列表中的逗号会导致解析失败。

这个问题仍然悬而未决,但委员会的共识是它应该起作用(尽管我不知道要改变什么才能使其有效)。

Clang 已经实现了一段时间的解决方法(可能暂时解析表达式并在失败时重试)而 Nathan Sidwell 刚刚 un-suspended the relevant G++ bug and assigned it to himself所以我希望他计划尽快修复它。

关于c++ - 使用 new 表达式的非静态数据成员初始化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30546631/

相关文章:

c++ - 无法动态更新 LineSeries QML 类型

c++ - 无法在输出中获取正确的分数值

c++ - 在 C++ 中计算字符串的 MD5

c++ - 为什么我的程序在 boost::enable_shared_from_this<>/boost::shared_ptr<> 中崩溃?

C++0x 可变参数模板通过引用传递

c++ - 获取 CAN 比特率

c++ - 为什么我在此 C++ 代码中得到 undefined reference ?

c++ - Qt 创建的应用程序在没有 Qt creator 的情况下无法运行

c++ - Snort 错误 : plugbase. c: undefined reference : "Setup"

c - 为什么在两个内核之间的邮箱数据通信中需要两个内存屏障?