将共享指针指向具有初始化的新结构

Making a shared pointer to a new struct with initialisation

本文关键字:新结构 结构 初始化 指针 共享      更新时间:2023-10-16

使用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}} );