【问题标题】:Using new with decltype将 new 与 decltype 一起使用
【发布时间】: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 &amp; 而不是 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 为你毁了它

标签: c++ c++11 decltype


【解决方案1】:

如果它们在同一行,您可以使用auto 只命名T 一次:

auto t = new T;

否则,您可以创建一个小函数模板:

template <class T>
void do_new(T * &p) {
  p = new T;
}


// Usage:
int main()
{
  T *t;
  do_new(t);
}

正如@MadScienceDreams 指出的那样,您可以扩展它以允许非默认构造函数:

template <class T, class... Arg>
void do_new(T * &p, Arg &&... arg) {
  p = new T(std::forward<Arg>(arg)...);
}


// Usage:
int main()
{
  T *t;
  do_new(t);
  std::string *s;
  do_new(s, "Abc");
}

【讨论】:

  • 漂亮。我会继续将“do_new”设为可变参数模板,以便 new 可以有参数。
  • @MadScienceDreams 完成。我假设您的意思是构造函数而不是分配函数的参数:-)
【解决方案2】:

std::remove_pointer&lt;decltype(t)&gt;::type 更具表现力/清晰。

如果重复多次,您也可以使用本地 typedef,否则会使某行变得过长/复杂。

【讨论】:

    猜你喜欢
    • 2012-11-17
    • 2013-03-07
    • 2013-07-03
    • 2011-09-27
    • 2015-04-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多