C++ 11/14/17 确实支持 "auto new"
C++ 11/14/17 does support "auto new"
将类似的指针声明为
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++中被认为是一种糟糕的做法),并且每次出现指针时都必须减少键入。
相关文章:
- 编译时未启用intel oneApi CUDA支持
- POCO::PostgreSQL:如何将std::vector支持添加到`Binder::bind`
- 使用CMake检测支持的C++标准
- 为什么istream不支持右值提取
- 当我编译webrtc服务器时,Windows上只支持clang-cl
- 扩展光电二极管探测器以支持多个传感器
- MSVC是否支持C++11样式的属性而不是__declspec
- 如果"new int"返回"int*",那么为什么"new int[n]"不返回"int**"?
- 有没有一种方法可以使用placement new将堆叠对象分配给分配的内存
- 重载运算符new[]的行为取决于析构函数
- 在使用GPU支持编译Tensorflow时,会遇到CUDA_TOOLKIT_PATH未绑定变量
- 当使用比格式支持的精度更高的精度来显示数字时,会写出什么数据
- 过载'operator new'如何导致无限循环?
- 创建具有 new in 函数和"this is nullptr"异常的对象
- Codelite C++ new project
- 在类c++中使用new声明数组
- g++用户定义的动态链接库上的全局new和delete运算符
- 如果整个应用程序是虚拟映射的,为什么 new 会进行系统调用?
- 在将 new 与指针一起使用时,创建数组的指定长度
- C++ 11/14/17 确实支持 "auto new"