c++ - Storing lvalue reference to a dynamically allocated array -
consider following class of custom array
template <typename element, unsigned int size> class array { private: element (&data)[size]; public: array(element (&reference)[size]):data(reference){} array():data(new element [size]){} // problem arises };
obviously, in initialization list of constructor evaluates rvalue expression (the new-expression) rvalue of pointer instead of reference type. in msvc (microsoft visual studio 2012 rc) prompts error type conversion element * element (&)[size].
however, think if can perhaps convert rvalue pointer reference, should compile. there chance can make there in initialization list of constructor? or perhaps conflicts principle of c++ language? i've investiaged reinterpret_cast, rule find relevant is
"an lvalue expression of type t1 can converted reference type t2. result lvalue or xvalue referring same object original lvalue, different type." - cppreference.com
which states conversion applies lvalue expression.
ok, know might think - why need such class of custom array , why don't composite pointer instead of problemtic reference? well...you need different approaches choose before knowning best don't you?
what's c++11 , rvalue references? lvalue expression value pointed pointer, use unary *
operator. it's been part of language since beginning. have here make sure pointer array, rather pointer first element of array.
template <typename element, unsigned int size> class array { private: element (&data)[size]; public: array() : data(*new element[1][size]) { } array(element (&reference)[size]) : data(reference) { } };
as mentioned mat in comment, parameterless constructor here bad idea, because memory not freed. hopefully, having working code sample allow experiment bit , come same conclusion.
Comments
Post a Comment