lhahn
lhahn

Reputation: 1241

Crazy unique_ptr syntax

I was recently using this syntax for a pointer:

std::vector<Shader *>* _shaderArray;

The problem is that I started to get memory leak errors. So now I decided to use unique_pointers, so I don't have to worry about this anymore. But from what I understood the above syntax in c++11 syntax is:

std::unique_ptr<std::vector<std::unique_ptr<Shader>>> _shaderArray;

If that is right, how do I initialize it? this code gives me errors:

_shaderArray = new std::vector<Shader *>( );

Upvotes: 0

Views: 231

Answers (2)

vsoftco
vsoftco

Reputation: 56547

Initialize the unique_ptr at declaration,

std::unique_ptr<std::vector<std::unique_ptr<Shader>>> _shaderArray{new std::vector<std::unique_ptr<Shader>>( )};

Full (compilable) minimal example:

#include <vector>
#include <memory>

class Shader{};

int main() 
{
    std::unique_ptr<std::vector<std::unique_ptr<Shader>>> _shaderArray{new std::vector<std::unique_ptr<Shader>>( )};
}

Upvotes: 2

glampert
glampert

Reputation: 4411

In your specific case, I would recommend the use of a typedef or using alias to simplify that very long statement:

using ShaderPtrVec = std::vector<std::unique_ptr<Shader>>;

using ShaderPtrVecPtr = std::unique_ptr<ShaderPtrVec>;

Then, using it becomes a bit more clear:

ShaderPtrVecPtr shaderArray( new ShaderPtrVec( ) );

Or, if you happen to have already declared the unique pointer but need to re-assign its contents, you can use reset:

shaderArray.reset( new ShaderPtrVec( ) );

Upvotes: 1

Related Questions