consider the following: I have a class A with a constructor which takes an array of ints of size 3 as argument.
Now I want to construct a shared_ptr to A. If I use
shared_ptr<>(new A (parameter))
everything is fine.
But if I try using
make_shared<A>(parameter)
the compiler gives an error message. This happens only if the parameter-array is declared on the stack AND with a variable as array size (int parameter [n])
The problem disappears when using static arrays (int parameter[3]) or allocating the array on the heap with new.
I mean, this is no serious issue as there are the mentioned workarounds. Still, I would appreciate any explanation on why whis happens...
Btw I'm using g++ 4.8.2.
Here is a minimal example and the error log:
#include <iostream>
#include <memory>
using namespace std;
// some simple class
class A
{
public:
A () {};
A (int var[3]) {}; // some non-default constructor with an array as argument
void foo (){cout << "foo()" << endl;};
};
int main()
{
// make a shared_ptr to A
shared_ptr<A> ptr;
// allocate an array var1 of size nVars=3 on the stack
int nVars = 3;
int var1[nVars];
ptr = shared_ptr<A> (new A(var1)); // without make_shared, the c'tor is recognized
ptr->foo();
ptr = make_shared<A> (var1); // <- error at compile time!
ptr->foo();
// same with static array var2 of size 3
int var2[3];
ptr = make_shared<A> (var2); // <- no compilation error
ptr->foo();
// same with dynamic array var3 of size 3
int* var3 = new int[nVars];
ptr = make_shared<A> (var3); // <- no compilation error
ptr->foo();
return 0;
}
build log:
g++ -std=c++0x -D__GXX_EXPERIMENTAL_CXX0X__ -O0 -g3 -Wall -c -fmessage-length=0 -MMD -MP -MF"main.d" -MT"main.d" -o "main.o" "../main.cpp"
../main.cpp: In function ‘int main()’:
../main.cpp:25:28: error: no matching function for call to ‘make_shared(int [(((sizetype)(((ssizetype)nVars) + -1)) + 1)])’
ptr = make_shared<A> (var1); // <- error at compile time!
^
../main.cpp:25:28: note: candidate is:
In file included from /usr/include/c++/4.8/memory:82:0,
from ../main.cpp:2:
/usr/include/c++/4.8/bits/shared_ptr.h:610:5: note: template<class _Tp, class ... _Args> std::shared_ptr<_Tp1> std::make_shared(_Args&& ...)
make_shared(_Args&&... __args)
^
/usr/include/c++/4.8/bits/shared_ptr.h:610:5: note: template argument deduction/substitution failed:
../main.cpp:25:28: note: variable-sized array type ‘int (&)[(((sizetype)(((ssizetype)nVars) + -1)) + 1)]’ is not a valid template argument
ptr = make_shared<A> (var1); // <- error at compile time!
^
Cheers and thanks in advance for your answers!
Juri