C++ 11/14/17 确实支持 "auto new"

C++ 11/14/17 does support "auto new"

本文关键字:支持 new auto C++      更新时间:2023-10-16

将类似的指针声明为

CAMArrayRefHash<AMPSDK::H264Video::SEQ_PARAMETER_SET_RBSP>* h264_sps;

当最后为它创建一个实例时:

h264_sps = new CAMArrayRefHash<AMPSDK::H264Video::SEQ_PARAMETER_SET_RBSP>();

在C++11/14/17中有一个简单的方法吗?例如,自动新

h264_sps = auto new;
#include <utility>
#include <iterator>
int main()
{
  int* p;
  p = new std::decay_t<decltype(*p)>;
  p = new std::iterator_traits<decltype(p)>::value_type();
}

或者我们可以创造性地使用模板参数推导:

#include <utility>
#include <iterator>
template<class Ptr, class...Args>
Ptr make_new(Ptr& p, Args&&...args)
{
  p = new std::decay_t<decltype(*p)>(std::forward<Args>(args)...);
  return p;
}
int main()
{
  int* p;
  // warning: initialises p  
  make_new(p);
  // initalise p and return a copy to ease use in algorithms  
  auto pcopy = make_new(p);
}

如果您使用的是C++11/14/17,只需使用smart_pointers和关键字组合使用

using RBSP = AMPSDK::H264Video::SEQ_PARAMETER_SET_RBSP; 
//if it's shared resource use **shared_ptr**
std::shared_ptr<RBSP> h264_sps{};
//if it's owned only by a class / struct,
std::unique_ptr<RBSP> h264_sps_unique{};
//after some lines of code or in another file...
h_264_sps = std::make_shared<RBSP>();
//Only in C++14/17:
h264_sps_unique = std::make_unique<RBSP>();

使用此解决方案,可以避免裸指针(这在现代C++中被认为是一种糟糕的做法),并且每次出现指针时都必须减少键入。