J Bramble
J Bramble

Reputation: 237

Making a shared pointer to a new struct with initialisation

Using libc++ (GNU++11 dialect), LLVM compiler, in Xcode on a Mac.

I have a struct as follows:

struct Vertex
{
    float position[3];
    float colour[4];
    float normal[3];
};

Currently I'm creating an instance on the heap as follows:

Vertex *vertex = new Vertex({{0.1f, 0.1f, 0.1f},
                            {0.0f, 0.0f, 0.0f, 0.0f},
                            {1.0f, 0.0f, 0.0f}} );

However I want to create a shared pointer instead. Is the following code the best way of doing it?

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);

Or should I be creating the Vertex using new before making a shared pointer?

Update

I've tried the following:

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

as suggested, but I get error no matching function for call to 'make_shared'.

Upvotes: 4

Views: 3110

Answers (1)

felix
felix

Reputation: 2220

In the first code snippet (the one right before your update), std::make_shared will allocate memory for a new Vector and construct it with the given argument v, in this case, copy construct. It will work fine.

The second code snippet (in your update) doesn't work because the compiler can't deduce a proper type which matches the argument. The function template std::make_shared is declared as:

template< class T, class... Args >
shared_ptr<T> make_shared( Args&&... args );

This problem can be solved by a "conversion".

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

Upvotes: 5

Related Questions