How do I instantiate
unique_ptr<int[]> sums;
in
int main(int argc, char** argv)
{
int n = //get from args
sums(new int[n]);
}
? It gives me the following compile-time error
error C2247: 'std::default_delete<_Ty>::operator ()' not accessible because 'std::unique_ptr>' uses 'private' to inherit from 'std::_Unique_ptr_base<_Ty,_Dx,true>'
It looks like you might be confused about C++'s constructor call syntax.
If you say
unique_ptr<int[]> sums(new int[n]);
That constructs a new object called sums
, calling the constructor with the pointer to the int array.
If you say
unique_ptr<int[]> sums;
sums(new int[n]);
It constructs sums
using the 0 argument constructor in the first line, then in the second line tries to call unique_ptr<int[]>::operator()(int*)
(ie, the function call operator) on the sums
object. This does not exist, which gives you the error.
As dauphic's answer says, the function you're looking for is called reset
:
sums.reset(new int[n]);
(You might be wondering why something so silly as a function call operator exists. It's there to allow you to create an object that can be called like a function, but passed around like a value.)
You're attempting to invoke sums
as if it's a function, which it's not. The internals of std::unique_ptr
make the error message confusing/misleading.
If you want to initialize what sums
points to, you should use the reset
function.
sums.reset(new int[n]);
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