Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to instantiate a global smart pointer variable?

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>'

like image 416
Ondrej Janacek Avatar asked Nov 08 '13 19:11

Ondrej Janacek


2 Answers

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.)

like image 115
Dan Avatar answered Sep 22 '22 04:09

Dan


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]);
like image 42
Collin Dauphinee Avatar answered Sep 23 '22 04:09

Collin Dauphinee