【发布时间】:2014-10-08 04:22:03
【问题描述】:
T *t; //T is an implementation detail
t = new T; //want to avoid naming T to allow for flexibility
t = new decltype(*t); //error: cannot use 'new' to allocate a reference
t = new std::remove_reference<decltype(*t)>::type(); //clunky
This 回答了为什么 decltype(*t) 返回 T & 而不是 T。
我可以将我的最后一行放入宏中,但这似乎不是最理想的。 有没有比我到目前为止更好的解决方案?这属于Code Review吗?
【问题讨论】:
-
+1,这当然属于 SO。
-
关于这是否属于 Code Review 或不属于 Meta 的问题。 :)
-
在 C++11 中,您不应该使用原始指针。使用
std::unique_ptr。也不要写new,实现你自己的std::make_unique(或使用像GCC 4.9这样的编译器或已经拥有它的最新MSVC++)并使用它。 -
避免命名
T的常用方法是提供一个适当的typedef,该typedef可由库所有者进行调整。我没有看到到处 隐藏 类型的意义......再说一次,我不相信 几乎总是自动 布道。 -
实际上,在孤立的情况下,
*t是T:) 你得到一个左值,它不是参考。decltype为你毁了它