Trouble constructing shared_ptr

705 views Asked by At

I'm new to smart pointers, and I'm in the process of hitting every stumbling block.

I have a struct texture_t:

struct texture_t
{
    hash32_t hash;
    uint32_t width;
    uint32_t height;
    uint32_t handle;
};

When I try and make a shared_ptr of this struct using this line:

auto texture_shared_ptr = std::make_shared<texture_t>(new texture_t());

I get this error:

error C2664: 'mandala::texture_t::texture_t(const mandala::texture_t &)' : cannot convert parameter 1 from 'mandala::texture_t *' to 'const mandala::texture_t &'

Where is this error coming from and how can I avoid it?

2

There are 2 answers

1
juanchopanza On BEST ANSWER

You are not supposed to pass a newed pointer to std::make_shared. You just need to pass arguments from which a texture_t can be constructed to it.

0
Dietmar Kühl On

The point of std::make_shared<T>(args...) is to allocate a T object constructed with parameters args.... The idea behind this operation is that std::shared_ptr<T> conceptually maintains two allocated objects:

  1. A pointer to type T.
  2. A record tracking the number of current std::shared_pt<T> and the number of std::weak_ptr<T> objects referring to the object.

When constructing a std::shared_ptr<T> the constructor does a second allocation to construct the record for its internal book keeping. std:make_shared<T>(args...) does just one memory allocation.

The error you saw results from an attempt to construct a mandala::texture_t using a mandala::texture_t* but the only one argument constructor mandala::texture_t has is the copy constructor. However, the pointer doesn't qualify as argument to the copy constructor.