将共享指针指向具有初始化的新结构
Making a shared pointer to a new struct with initialisation
使用libc (gnu 11方言),llvm编译器,在mac上的xcode中。
我的结构如下:
struct Vertex
{
float position[3];
float colour[4];
float normal[3];
};
目前我正在堆上创建一个实例,如下所示:
Vertex *vertex = new Vertex({{0.1f, 0.1f, 0.1f},
{0.0f, 0.0f, 0.0f, 0.0f},
{1.0f, 0.0f, 0.0f}} );
但是,我想创建一个共享指针。以下代码是最好的方法吗?
Vertex v = Vertex( {{0.1f, 0.1f, 0.1f},
{0.0f, 0.0f, 0.0f, 0.0f},
{1.0f, 0.0f, 0.0f}} );
std::shared_ptr<Vertex> vertex = std::make_shared<Vertex>(v);
或在制作共享指针之前,我应该使用new
创建Vertex
?
update
我尝试了以下内容:
auto vertex = std::make_shared<PCNVertex>( {{0.1f, 0.1f, 0.1f},
{0.0f, 0.0f, 0.0f, 0.0f},
{1.0f, 0.0f, 0.0f}} );
建议,但我会收到错误 no matching function for call to 'make_shared'
。
在第一个代码段(更新之前的一个)中,std::make_shared
将为新的Vector
分配内存,并使用给定参数v
构造它,在这种情况下,请复制构造。它可以正常工作。
第二个代码段(在您的更新中)不起作用,因为编译器无法推断出与参数匹配的适当类型。函数模板std :: make_shared被声明为:
template< class T, class... Args >
shared_ptr<T> make_shared( Args&&... args );
可以通过"转换"来解决此问题。
auto vertex = std::make_shared<Vertex>(
Vertex{{0.1f, 0.1f, 0.1f},
{0.0f, 0.0f, 0.0f, 0.0f},
{1.0f, 0.0f, 0.0f}} );
相关文章:
- C++:添加新结构时,结构指针向量中的所有元素都会更新
- 为什么Microsoft在新代码中使用结构而不是类?
- c ++数据输入并读回列表中的结构结构中的数组
- 如何创建结构的结构结构,等等嵌套多个结构?
- 当我尝试为结构分配新指针时出现堆栈溢出错误
- 是复制了新数组还是指向结构中引用的数组的指针?
- 是否需要删除函数中未使用的新结构?
- 使用带有结构结构作为 C++; 元素的单向链表
- 有没有办法初始化不涉及编写构造函数的新结构变量?
- 结构 + initializer_list 的聚合初始化:新与静态
- 是否可以在没有结构的情况下创建新的类型变量?
- 结构指针在"新"调用上给出已分配的地址?
- 在使用新操作员和C 中的结构的调用构造函数时,获得内存损坏(Malloc)
- 易失性结构 = 结构不可能,为什么?
- cpp 中是否存在一种数据结构,可以轻松地提供一种基于已存在的实例构建新结构的方法
- 返回带有动态结构数组的结构结构
- 功能指针强制沿着班级结构结构
- 遵循来自源文件的结构结构
- 可变类/结构结构?(不是模板而不是工会?
- 标准异常层次结构结构的原因