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