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'
.
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}} );
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With