Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Assign a dynamically allocated array in a constructor to a unique smart pointer member variable

In the example below, I have a smart pointer sp as a member variable and I want to assign a dynamically allocated array to it in the constructor, however I get a compiler error no match for ‘operator=’, what is the correct way to do this?

In the example below, I have a smart pointer sp as a member variable and I want to assign a dynamically allocated array to it in the constructor, is using the reset() method of smart pointer the correct way to do this or should I be using a shared smart pointer?

struct SampleStructure
{
std::unique_ptr<idx_t[]> sp;

SampleStructure(int a, int b){

    sp.reset(new idx_t[a + 1]); 
 }
};
like image 628
clonard reilly Avatar asked Sep 07 '25 07:09

clonard reilly


1 Answers

You can't use operator= because std::unique_ptr can't be assigned from raw pointers directly, as you showed, you have to use reset(), which would replace the managed object (after the initialization of the unique_ptr).

You can initialize the data member sp via member initializer list in the constructor directly; then you don't need the "assignment" (replacement). e.g.

SampleStructure(int a, int b) : sp(std::make_unique<idx_t[]>(a + 1)) {}
like image 93
songyuanyao Avatar answered Sep 10 '25 03:09

songyuanyao