0

I'm trying to compile a simple shared pointer declaration but using g++ -std=c++11 main.cpp -o main using cmd but due to some reasons it throws a bunch of errors. I tried finding similar questions on Stack Overflow but none of them matches my problem.

code:

std::shared_ptr<int[]>array(new int[100]);

Header files:

#include<iostream>
#include<memory>

compiler version: g++ (MinGW.org GCC-6.3.0-1) 6.3.0

Error:

In file included from c:\mingw\lib\gcc\mingw32\6.3.0\include\c++\bits\shared_ptr.h:52:0,
                 from c:\mingw\lib\gcc\mingw32\6.3.0\include\c++\memory:82,
                 from main.cpp:2:
c:\mingw\lib\gcc\mingw32\6.3.0\include\c++\bits\shared_ptr_base.h: In instantiation of 'std::__shared_ptr<_Tp, _Lp>::__shared_ptr(_Tp1*) [with _Tp1 = int; _Tp = int []; __gnu_cxx::_Lock_policy _Lp = (__gnu_cxx::_Lock_policy)2u]':
c:\mingw\lib\gcc\mingw32\6.3.0\include\c++\bits\shared_ptr.h:117:32:   required from 'std::shared_ptr<_Tp>::shared_ptr(_Tp1*) [with _Tp1 = int; _Tp = int []]'
main.cpp:7:42:   required from here
c:\mingw\lib\gcc\mingw32\6.3.0\include\c++\bits\shared_ptr_base.h:885:39: error: cannot convert 'int*' to 'int (*)[]' in initialization
         : _M_ptr(__p), _M_refcount(__p)
                                       ^`

I'm relatively new and don't know what this error means. Any suggestions would be helpful.

1201ProgramAlarm
  • 32,384
  • 7
  • 42
  • 56

2 Answers2

2

Prior to C++17, std::shared_ptr could not handle dynamically allocated arrays. Upgrade your compiler to support C++17 and your code will happily compile.

EDIT: There is a workaround for earlier versions. You could use:

std::shared_ptr<int> sp(new int[10], custom_deleter<int>{});

where custom_deleter will be a function that will be used to free the allocated memory. In this case, simple delete[] (instead of implicit delete inside shared_ptrs destructor) will be enough:

template< typename T >
struct custom_deleter
{
    void operator ()(const T* arr)
    { 
        delete[] arr; 
    }
};

but since you are already using C++11, one could replace the struct with a lambda expression, which will simplify the code:

std::shared_ptr<int> sp(new int[10], [](const int* arr){ delete[] arr; });
Fureeish
  • 12,533
  • 4
  • 32
  • 62
1

The "cannot convert ..." error is a type error, it means that you've used the wrong data type. In this case, it's specifically telling you that the constructor for std::shared_ptr<int[]> wants a int (*)[] argument type, but you're providing an argument of type int *. Since the compiler doesn't know how to convert from int * to int (*)[], you're getting this error.

In any case, you shouldn't be using shared_ptr to manage C-style arrays. I'd advise switching to STL containers, either std::array<int, N> or std::vector<int> depending on whether you know the size at compile time or not. Any STL container type can then be put into a smart pointer, if you like.

JMAA
  • 1,730
  • 13
  • 24