Strange warnings when using my array class - c++

I've written a pretty simple array class in C++ and use it in my application:
/* A simple array class template that performs dynamic */
/* memory management and casting to (T*), which allows */
/* to use it as a usual array. */
template <typename T>
class Array
{
public:
//Constructor
Array(unsigned long size)
{
try
{
data = new T[size];
m_size = size;
}
catch(...)
{
cout << "Could not allocate " << size << " bytes." << endl;
data = NULL; m_size = 0;
}
}
//Typecast operator
operator T*() { assert(data!=NULL); return data; }
//Subscript operator
T& operator[] (unsigned long Index);
//Destructor
~Array() { if(data!=NULL) delete[] data; }
private:
T * data;
unsigned long m_size;
};
template<typename T>
T& Array<T>::operator[] (unsigned long Index)
{
assert(Index<m_size);
assert(data!=NULL);
return data[Index];
}
However, when I use it like this:
Array<char> filename(5);
filename[0] = SomeVar;
GCC ouputs the following warning:
warning: ISO C++ says that these are ambiguous, even though the worst conversion for the first is better than the worst conversion for the second: [enabled by default]
note: candidate 1: T& Array<T>::operator[](long unsigned int) [with T = char]
note: candidate 2: operator[](char*, int) <built-in>
What is the reason? How can I solve it?

The reason is quite simple: for your filename[0] the compiler can use your operator[], or it can convert filename to char* using your type conversion operator, and then apply operator[] to a char pointer.
More explicitly, what happening is
filename.Array<char>::operator[](0)
vs
filename.Array<char>::operator char*().operator[](0)
(don't know whether the latter is correct c++, but it gives an idea of what happening)
P.S. Almost sure this should have been asked before, but was not able to find a duplicate.

Related

Difference between: std::make_unique<char>(size_t size) and std::make_unique<char[]>(size_t size)?

I was implementing the circular array data structure whose code looks like this:
struct CircularArrayException : public std::exception {
std::string msg;
CircularArrayException(const std::string arg_msg)
: msg{"CircularArrayException: " + arg_msg} {}
const char * what () const throw () {
return msg.c_str();
}
};
template <typename T>
class CircularArray {
public:
const size_t array_size;
std::unique_ptr<T> uptr_arr;
size_t occupied_size = 0;
int front_idx = -1;
int back_idx = -1;
CircularArray(const CircularArray& ca) = delete;
CircularArray& operator=(const CircularArray& ca) = delete;
CircularArray(
const size_t arg_array_size
): array_size{arg_array_size} {
uptr_arr = std::make_unique<T>(array_size);
};
};
After the implementation I tested the implementation with CircularArray<char> and it works fine.
But, then I realized that we use std::make_unique<char[]>(num_elements) to declare a unique_ptr to an array as opposed to std::make_unique<char>(num_elements). But, even then the code seems to work fine. I looked the documentation of std::make_unique here and couldn't understand the explanation of the (2)nd signature. Can anyone help me out to understand the difference and why my code works?
Here is the what is written on cppreference for the (2) signature:
template< class T >
unique_ptr<T> make_unique( std::size_t size );
(2) (since C++14)
(only for array types with unknown bound)
Constructs an array of unknown bound T. This overload participates in overload resolution only if T is an array of unknown bound. The function is equivalent to: unique_ptr<T>(new typename std::remove_extent<T>::type[size]())
Here is the goldbolt link: https://godbolt.org/z/K9h3qTeTW
std::make_unique<char>(65); creates a pointer to a single character initialised with the value 65 ('A'). std::make_unique<char[]>(65) creates an array with 65 elements.
If you run this code:
#include <memory>
#include <iostream>
int main()
{
auto a = std::make_unique<char>(65);
std::cout << *a << "\n";
auto b = std::make_unique<char[]>(65);
std::cout << (int)b[0] << "\n";
}
It'll print A for the first one and an undefined value for the second one (possibly 0) as the array elements are uninitialised.
Your code "works" by chance, using any more than 1 element of your "array" will cause undefined behaviour.

c++ send arguments to union (variable union)

well i cant find how do this, basically its a variable union with params, basic idea, (writed as function)
Ex1
union Some (int le)
{
int i[le];
float f[le];
};
Ex2
union Some
{
int le;
int i[le];
float f[le];
};
obs this don't works D:
maybe a way to use an internal variable to set the lenght but don't works too.
Thx.
No, this is not possible: le would need to be known at compile-time.
One solution would be to use a templated union:
template <int N> union Some
{
int i[N];
float f[N];
};
N, of course, is compile-time evaluable.
Another solution is the arguably more succinct
typedef std::vector<std::pair<int, float>> Some;
or a similar solution based on std::array.
Depending on your use case you could try to simulate a union.
struct Some
{
//Order is important
private:
char* pData;
public:
int* const i;
float* const f;
public:
Some(size_t len)
:pData(new char[sizeof(int) < sizeof(float) ? sizeof(float) : sizeof(int)])
,i ((int*)pData)
,f ((float*)pData)
{
}
~Some()
{
delete[] pData;
}
Some(const Some&) = delete;
Some& operator=(const Some&) = delete;
};
Alternative solution using templates, unique_ptr and explicit casts:
//max_size_of<>: a recursive template struct to evaluate the
// maximum value of the sizeof function of all types passed as
// parameter
//The recursion is done by using the "value" of another
// specialization of max_size_of<> with less parameter types
template <typename T, typename...Args>
struct max_size_of
{
static const std::size_t value = std::max(sizeof(T), max_size_of<Args...>::value);
};
//Specialication for max_size_of<> as recursion stop
template <typename T>
struct max_size_of<T>
{
static const std::size_t value = sizeof(T);
};
//dataptr_auto_cast<>: a recursive template struct that
// introduces a virtual function "char* const data_ptr()"
// and an additional explicit cast operator for a pointer
// of the first type. Due to the recursion a cast operator
// for every type passed to the struct is created.
//Attention: types are not allowed to be duplicate
//The recursion is done by inheriting from of another
// specialization of dataptr_auto_cast<> with less parameter types
template <typename T, typename...Args>
struct dataptr_auto_cast : public dataptr_auto_cast<Args...>
{
virtual char* const data_ptr() const = 0; //This is needed by the cast operator
explicit operator T* const() const { return (T*)data_ptr(); } //make it explicit to avoid unwanted side effects (manual cast needed)
};
//Specialization of dataptr_auto_cast<> as recursion stop
template <typename T>
struct dataptr_auto_cast<T>
{
virtual char* const data_ptr() const = 0;
explicit operator T* const() const { return (T*)data_ptr(); }
};
//union_array<>: inherits from dataptr_auto_cast<> with the same
// template parameters. Also has a static const member "blockSize"
// that indicates the size of the largest datatype passed as parameter
// "blockSize" is used to determine the space needed to store "size"
// elements.
template <typename...Args>
struct union_array : public dataptr_auto_cast<Args...>
{
static const size_t blockSize = max_size_of<Args...>::value;
private:
std::unique_ptr<char[]> m_pData; //std::unique_ptr automatically deletes the memory it points to on destruction
size_t m_size; //The size/no. of elements
public:
//Create a new array to store "size" elements
union_array(size_t size)
:m_pData(new char[size*blockSize])
,m_size(size)
{
}
//Copy constructor
union_array(const union_array<Args...>& other)
:m_pData(new char[other.m_size*blockSize])
,m_size(other.m_size)
{
memcpy(m_pData.get(), other.m_pData.get(), other.m_size);
}
//Move constructor
union_array(union_array<Args...>&& other)
:m_pData(std::move(other.m_pData))
,m_size(std::move(other.m_size))
{
}
union_array& operator=(const union_array<Args...>& other)
{
m_pData = new char[other.m_size*blockSize];
m_size = other.m_size;
memcpy(m_pData.get(), other.m_pData.get(), other.m_size);
}
union_array& operator=(union_array<Args...>&& other)
{
m_pData = std::move(other.m_pData);
m_size = std::move(other.m_size);
}
~union_array() = default;
size_t size() const
{
return m_size;
}
//Implementation of dataptr_auto_cast<>::data_ptr
virtual char* const data_ptr() const override
{
return m_pData.get();
}
};
int main()
{
auto a = union_array<int, char, float, double>(5); //Create a new union_array object with enough space to store either 5 int, 5 char, 5 float or 5 double values.
((int*)a)[3] = 3; //Use as int array
auto b = a; //copy
((int*)b)[3] = 1; //Change a value
auto c = std::move(a);// move a to c, a is invalid beyond this point
// std::cout << ((int*)a)[3] << std::endl; //This will crash as a is invalid due to the move
std::cout << ((int*)b)[3] << std::endl; //prints "1"
std::cout << ((int*)c)[3] << std::endl; //prints "3"
}
Explanation
template <typename T, typename...Args>
struct max_size_of
{
static const std::size_t value = std::max(sizeof(T), max_size_of<Args...>::value);
};
template <typename T>
struct max_size_of<T>
{
static const std::size_t value = sizeof(T);
};
max_size_of<> is used to get the largest sizeof() value of all types passed as template paremeters.
Let's have a look at the simple case first.
- max_size_of<char>::value: value will be set to sizeof(char).
- max_size_of<int>::value: value will be set to sizeof(int).
- and so on
If you put in more than one type it will evaluate to the maximum of the sizeof of these types.
For 2 types this would look like this: max_size_of<char, int>::value: value will be set to std::max(sizeof(char), max_size_of<int>::value).
As described above max_size_of<int>::value is the same as sizeof(int), so max_size_of<char, int>::value is the same as std::max(sizeof(char), sizeof(int)) which is the same as sizeof(int).
template <typename T, typename...Args>
struct dataptr_auto_cast : public dataptr_auto_cast<Args...>
{
virtual char* const data_ptr() const = 0;
explicit operator T* const() const { return (T*)data_ptr(); }
};
template <typename T>
struct dataptr_auto_cast<T>
{
virtual char* const data_ptr() const = 0;
explicit operator T* const() const { return (T*)data_ptr(); }
};
dataptr_auto_cast<> is what we use as a simple abstract base class.
It forces us to implement a function char* const data_ptr() const in the final class (which will be union_array).
Let's just assume that the class is not abstract and use the simple version dataptr_auto_cast<T>:
The class implements a operator function that returns a pointer of the type of the passed template parameter.
dataptr_auto_cast<int> has a function explicit operator int* const() const;
The function provides access to data provided by the derived class through the data_ptr()function and casts it to type T* const.
The const is so that the pointer isn't altered accidentially and the explicit keyword is used to avoid unwanted implicit casts.
As you can see there are 2 versions of dataptr_auto_cast<>. One with 1 template paremeter (which we just looked at) and one with multiple template paremeters.
The definition is quite similar with the exception that the multiple parameters one inherits dataptr_auto_cast with one (the first) template parameter less.
So dataptr_auto_cast<int, char> has a function explicit operator int* const() const; and inherits dataptr_auto_cast<char> which has a function explicit operator char* const() const;.
As you can see there is one cast operator function implemented with each type you pass.
There is only one exception and that is passing the same template parameter twice.
This would lead in the same operator function being defined twice within the same class which doesn't work.
For this use case, using this as a base class for the union_array, this shouldn't matter.
Now that these two are clear let's look at the actual code for union_array:
template <typename...Args>
struct union_array : public dataptr_auto_cast<Args...>
{
static const size_t blockSize = max_size_of<Args...>::value;
private:
std::unique_ptr<char[]> m_pData;
size_t m_size;
public:
//Create a new array to store "size" elements
union_array(size_t size)
:m_pData(new char[size*blockSize])
,m_size(size)
{
}
//Copy constructor
union_array(const union_array<Args...>& other)
:m_pData(new char[other.m_size*blockSize])
,m_size(other.m_size)
{
memcpy(m_pData.get(), other.m_pData.get(), other.m_size);
}
//Move constructor
union_array(union_array<Args...>&& other)
:m_pData(std::move(other.m_pData))
,m_size(std::move(other.m_size))
{
}
union_array& operator=(const union_array<Args...>& other)
{
m_pData = new char[other.m_size*blockSize];
m_size = other.m_size;
memcpy(m_pData.get(), other.m_pData.get(), other.m_size);
}
union_array& operator=(union_array<Args...>&& other)
{
m_pData = std::move(other.m_pData);
m_size = std::move(other.m_size);
}
~union_array() = default;
size_t size() const
{
return m_size;
}
virtual char* const data_ptr() const override
{
return m_pData.get();
}
};
As you can see union_array<> inherits from dataptr_auto_cast<> using the same template arguments.
So this gives us a cast operator for every type passed as template paremeter to union_array<>.
Also at the end of union_array<> you can see that the char* const data_ptr() const function is implemented (the abstract function from dataptr_auto_cast<>).
The next interesting thing to see is static const size_t blockSize which is initilialized with the maximum sizeof value of the template paremeters to union_array<>.
To get this value the max_size_of is used as described above.
The class uses std::unique_ptr<char[]> as data storage, as std::unique_ptr automatically will delete the space for us, once the class is destroyed.
Also std::unique_ptr is capable of move semantics, which is used in the move assign operator function and the move constructor.
A "normal" copy assign operator function and a copy constructor are also included and copy the memory accordingly.
The class has a constructor union_array(size_t size) which takes the number of elements the union_array should be able to hold.
Multiplying this value with blockSize gives us the space needed to store exactly size elements of the largest template type.
Last but not least there is an access method to ask for the size() if needed.
C++ requires that the size of a type be known at compile time.
The size of a block of data need not be known, but all types have known sizes.
There are three ways around it.
I'll ignore the union part for now. Imagine if you wanted:
struct some (int how_many) {
int data[how_many];
};
as the union part adds complexity which can be dealt with separately.
First, instead of storing the data as part of the type, you can store pointers/references/etc to the data.
struct some {
std::vector<int> data;
explicit some( size_t how_many ):data(how_many) {};
some( some&& ) = default;
some& operator=( some&& ) = default;
some( some const& ) = default;
some& operator=( some const& ) = default;
some() = default;
~some() = default;
};
here we store the data in a std::vector -- a dynamic array. We default copy/move/construct/destruct operations (explicitly -- because it makes it clearer), and the right thing happens.
Instead of a vector we can use a unique_ptr:
struct some {
std::unique_ptr<int[]> data;
explicit some( size_t how_many ):data(new int[how_many]) {};
some( some&& ) = default;
some& operator=( some&& ) = default;
some() = default;
~some() = default;
};
this blocks copying of the structure, but the structure goes from being size of 3 pointers to being size of 1 in a typical std implementation. We lose the ability to easily resize after the fact, and copy without writing the code ourselves.
The next approach is to template it.
template<std::size_t N>
struct some {
int data[N];
};
this, however, requires that the size of the structure be known at compile-time, and some<2> and some<3> are 'unrelated types' (barring template pattern matching). So it has downsides.
A final approach is C-like. Here we rely on the fact that data can be variable in size, even if types are not.
struct some {
int data[1]; // or `0` in some compilers as an extension
};
some* make_some( std::size_t n ) {
Assert(n >= 1); // unless we did `data[0]` above
char* buff = new some[(n-1)*sizeof(int) + sizeof(some)]; // note: alignment issues on some platforms?
return new(buff) some(); // placement new
};
where we allocate a buffer for some of variable size. Access to the buffer via data[13] is practically legal, and probably actually so as well.
This technique is used in C to create structures of variable size.
For the union part, you'll want to create a buffer of char with the right size std::max(sizeof(float), sizeof(int))*N, and expose functions:
char* data(); // returns a pointer to the start of the buffer
int* i() { return reinterpret_cast<int*>(data()); }
float* f() { return reinterpret_cast<float*>(data()); }
you may also need to properly initialize the data as the proper type; in theory, a char buffer of '\0's may not correspond to defined float values or ints that are zero.
I would like to suggest a different approach: Instead of tying the number of elements to the union, tie it outside:
union Some
{
int i;
float f;
};
Some *get_Some(int le) { return new Some[le]; }
Don't forget to delete[] the return value of get_Some... Or use smart pointers:
std::unique_ptr<Some[]> get_Some(int le)
{ return std::make_unique<Some[]>(le); }
You can even create a Some_Manager:
struct Some_Manager
{
union Some
{
int i;
float f;
};
Some_Manager(int le) :
m_le{le},
m_some{std::make_unique<Some[]>(le)}
{}
// ... getters and setters...
int count() const { return m_le; }
Some &operator[](int le) { return m_some[le]; }
private:
int m_le{};
std::unique_ptr<Some[]> m_some;
};
Take a look at the Live example.
It's not possible to declare a structure with dynamic sizes as you are trying to do, the size must be specified at run time or you will have to use higher-level abstractions to manage a dynamic pool of memory at run time.
Also, in your second example, you include le in the union. If what you were trying to do were possible, it would cause le to overlap with the first value of i and f.
As was mentioned before, you could do this with templating if the size is known at compile time:
#include <cstdlib>
template<size_t Sz>
union U {
int i[Sz];
float f[Sz];
};
int main() {
U<30> u;
u.i[0] = 0;
u.f[1] = 1.0;
}
http://ideone.com/gG9egD
If you want dynamic size, you're beginning to reach the realm where it would be better to use something like std::vector.
#include <vector>
#include <iostream>
union U {
int i;
float f;
};
int main() {
std::vector<U> vec;
vec.resize(32);
vec[0].i = 0;
vec[1].f = 42.0;
// But there is no way to tell whether a given element is
// supposed to be an int or a float:
// vec[1] was populated via the 'f' option of the union:
std::cout << "vec[1].i = " << vec[1].i << '\n';
}
http://ideone.com/gjTCuZ

C: var was not declared in this scope

I am attempting to get my array wrapper class to compile, but I'm new to c++. I keep getting a series of relating to the last function:
Line 81
Invalid Use of template-name 'warray' without an arugment list
Line 81
ISO C++ forbids declaration of 'parameter' with not type
line 81
error expected ',' or '...' before < town
line 83
rhs was not declared in this scope
and finally, line 86
rhs was not declared in this scope
This function is so confusing, and I think I implemented it all correct.
IDK! Please help!
#ifndef WARRAY
#define WARRAY
#include <iostream>
#include <stdexcept>
template <typename T>
class warray {
private:
unsigned int theSize;
T* theData;
public:
//will default to a size of 10 - bump to 10 if below
warray(unsigned int size = 10){
if(size < 10){
size = 10;
}
theSize = size;
theData = new T[theSize];
}
//copy
warray(const warray &rhs):theSize(rhs.theSize){
theData = new T[theSize];
//use assignment*this = rhs;
*this = rhs;
}
//assignment
warray & operator=(const warray &rhs){
//only resize array if lhs < than rhs//this also remedies
if(theSize < rhs.theSize){
delete [] theData;
theData = new T[rhs.theSize];
}
theSize = rhs.theSize;
for(unsigned int i = 0; i < theSize; ++i){
(*this);
}
return *this;
}
//destrctor
~warray(){
delete [] theData;
}
//operator+ will concatenate two arrays should be const
warray operator+(const warray &rhs) const{
warray toRet(theSize + rhs.size);
for(unsigned int i = 0; i < theSize; ++i){
toRet[i] = (*this)[i];
}
for(unsigned int i = 0; i < theSize; ++i){
toRet[i+theSize] = rhs[i];
}
return warray();
}
//operator[unsigned T index]
//will index and allow access to requested element
// - two versions, const and non-const
T operator[](unsigned int index) const{
if(index >= theSize){
throw std::out_of_range ("in operator [] ");
}
return theData[theSize];
}
//size
unsigned int size() const{
return theSize;
}
};
std::ostream &operator<< (std::ostream &os, const warray&<T> rhs){
os << "[ ";
for(unsigned i = 0; i < rhs.size()-1; ++i){
os << rhs[i] << " , ";
}
os << rhs[rhs.size() - 1] << " ]";
return os;
}
#endif
This line:
T *theData [theSize];
attempts to declare an array of pointers of size theSize, but theSize is not a constant and is not known at compile time. You also don't want an array of pointers to T, you want a pointer to an array of T.
change it to
T *theData;
There are other problems with your code. e.g. your << operator needs to be a template and I have no idea what (*this) is trying to achieve.
Note: I am assuming you are doing this for learning purposes and can't simply use a vector.
Edit: The "Invalid Use of template-name 'warray' without an argument list" error is caused by the << operator not having template<typename T> in front of it. It needs this to make it a templated function.
You have marked this as C++.
I recommend you change from:
class warray {
private:
unsigned int theSize;
T* theData;
And perhaps try:
class warray {
private:
std::vector<T> theData;
What you call "theSize" is now available as theData.size().
To append values of T, use push_back().
If you desire, you can allocate a start size using theData.reserve(size), but not necessary.
Remove
delete [] theData;
because you no longer 'new'd it in the ctor.
The vector's dtor will be called automagically when your warray instance is dtor'd.
Can't define theData this way:
T *theData[theSize];
defining the size of a static array with a variable is non-standard. Some compilers allow it, some don't. Best practice is not to do it so you don't get tripped up. As it is, the Size has no defined value at that point so even if your compiler did that trick, there is a ton of ka-boom potential.
Fortunately, based on the rest of the code, you don't need to. You keep defining the size of the array yourself, so:
T *theData;
Should do you just fine.

Why is my std::string getting converted to std::basic_string<char>?

Error
stack.cc:53:28: error: no matching function for call to ‘Stack<std::basic_string<char> >::push(std::string)’
stack.cc:53:28: note: candidate is:
stack.cc:32:11: note: Stack<T>& Stack<T>::push(T&) [with T = std::basic_string<char>]
stack.cc
#include<iostream>
template <typename T>
class Stack {
private:
T* array_;
int length_;
T* last_;
void expandArray();
public:
Stack(int length = 8) {
array_ = new T[length];
length_ = length;
last_ = array_;
}
Stack<T>& push(T&);
T pop();
};
template<typename T>
void Stack<T>::expandArray() {
T* array_temp = new T[length_ << 1];
memcpy(array_temp, array_, length_);
std::swap(array_, array_temp);
delete[] array_temp;
length_ <<= 1;
}
template<typename T>
Stack<T>& Stack<T>::push(T& data) {
if (last_ == (array_ + length_ - 1)) {
expandArray();
}
last_[0] = data;
last_++;
return *this;
}
template<typename T>
T Stack<T>::pop() {
if(array_ != last_) {
T temp = last_[0];
last_--;
return temp;
}
return NULL;
}
int main() {
Stack<std::string> s;
s.push(std::string("a"))
.push(std::string("b"))
.push(std::string("c"))
.push(std::string("d"));
std::cout << s.pop() << std::endl;
std::cout << s.pop() << std::endl;
std::cout << s.pop() << std::endl;
std::cout << s.pop() << std::endl;
}
Wanted to understand why a conversion is happening from std::string to std::basic_string<char>?
Please feel free to comment on the code quality as well.
The actual problem is that you're attempting to pass a reference to an object created in the argument rather than stored in a variable. See that T& argument to Stack<T>::push? You cannot pass your temporary here because it's a non-const reference. Try as follows...
Stack<T>& push(const T&);
Use this signature for your implementation, too.
That being said, know that std::string is a mere typedef over std::basic_string<char>. This is because the functionality for strings can be extended to the other character types, too -- std::wstring for wchar_t, std::u16string for char16_t, and std::u32string for char32_t. ;-)
See §21.4 Class template basic_string [basic.string] of the C++11 specification.
// basic_string typedef names
typedef basic_string<char> string;
typedef basic_string<char16_t> u16string;
typedef basic_string<char32_t> u32string;
typedef basic_string<wchar_t> wstring;
Note that you shouldn't rely on iostream to include string for you. You should also include cstring and specify the scope for your memcpy call.
By the way, you should really look into using an initializer list for Stack's constructor... see as follows.
Stack(int length = 8) : length_(length), array_(new T[length]), last_(array_) { }
Note that this functioning properly on array_ preceding last_ as a class member declaration ;-)
... AND a final note. Your pop is incorrect, since you're returning the element past the top. Instead, try something as follows...
template<typename T>
T Stack<T>::pop() {
if (array_ != last_) {
return *--last_;
}
/* other stuff here */
}
You need to decrement prior to dereferencing, since last_ points past the top. As a side note, you're also returning a copy of the std::string from pop, even though you stated you wanted to avoid as such.
Note you shouldn't be returning NULL since this isn't a pointer type. In fact, you'll just be creating an std::string via the constructor that takes a const char *... which is explicitly prohibited in the case of NULL. See §21.4.2¶8-9...
basic_string(const charT* s, const Allocator& a = Allocator());
Requires: s shall not be a null pointer.
std::string is a typedef for std::basic_string<char> it is not being converted to it, it is it. The reason is that the same std::basic_string template can be used with wchar_t to have unicode strings.
Because that is what std::string really is - it is just an alias for `std::basic_string':
typedef basic_string<char> string;
When the compiler is reporting the error message, it is displaying the typedef's real base type, not the alias name.

Array with undefined size as Class-member

I'm searching for a way to define an array as a class-member with an undefined size (which will be defined on initialization).
class MyArrayOfInts {
private:
int[] array; // should declare the array with an (yet) undefined length
public:
MyArrayOfInts(int);
int Get(int);
void Set(int, int);
};
MyArrayOfInts::MyArrayOfInts(int length) {
this->array = int[length]; // defines the array here
}
int MyArrayOfInts::Get(int index) {
return this->array[index];
}
void MyArrayOfInts:Set(int index, int value) {
this->array[index] = value;
}
How can I achieve this behaviour ?
Why not just use std::vector<int>?
Proof Of Concept
Ok, inspired by UncleBens challenge here, I came up with a Proof-Of-Concept (see below) that let's you actually do:
srand(123);
for (int i=0; i<10; i++)
{
size_t N = rand() % DEMO_MAX; // capped for demo purposes
std::auto_ptr<iarray> dyn(make_dynamic_array(N));
exercise(*dyn);
}
It revolves around a template trick in factory<>::instantiate that actually uses a compile-time meta-binary-search to match the specified (runtime) dimension to a range of explicit static_array class template instantiations.
I feel the need to repeat that this is not good design, I provide the code sample only to show what the limits are of what can be done - with reasonable effor, to achieve the actual goal of the question. You can see the drawbacks:
the compiler is crippled with a boatload of useless statical types and create classes that are so big that they become a performance liability or a reliability hazard (stack allocation anyone? -> we're on 'stack overflow' already :))
at DEMO_MAX = 256, g++ -Os will actually emit 258 instantiations of factory<>; g++ -O4 will keep 74 of those, inlining the rest[2]
compilation doesn't scale well: at DEMO_MAX = MAX_RAND compilation takes about 2m9s to... run out of memory on a 64-bit 8GB machine; at MAX_RAND>>16 it takes over 25 minutes to possibly compile (?) while nearly running out of memory. It would really require some amounts of ugly manual optimization to remove these limits - I haven't gone so insane as to actually do that work, if you'll excuse me.
on the upside, this sample demonstrates the arguably sane range for this class (0..256) and compiles in only 4 seconds and 800Kb on my 64-bit linux. See also a down-scaled, ANSI-proof version at codepad.org
[2] established that with objdump -Ct test | grep instantiate | cut -c62- | sort -k1.10n
Show me the CODE already!
#include <iostream>
#include <memory>
#include <algorithm>
#include <iterator>
#include <stdexcept>
struct iarray
{
typedef int value_type;
typedef value_type* iterator;
typedef value_type const* const_iterator;
typedef value_type& reference;
typedef value_type const& const_reference;
virtual size_t size() const = 0;
virtual iterator begin() = 0;
virtual const_iterator begin() const = 0;
// completely unoptimized plumbing just for demonstration purps here
inline iterator end() { return begin()+size(); }
inline const_iterator end() const { return begin()+size(); }
// boundary checking would be 'gratis' here... for compile-time constant values of 'index'
inline const_reference operator[](size_t index) const { return *(begin()+index); }
inline reference operator[](size_t index) { return *(begin()+index); }
//
virtual ~iarray() {}
};
template <size_t N> struct static_array : iarray
{
static const size_t _size = N;
value_type data[N];
virtual size_t size() const { return _size; }
virtual iterator begin() { return data; }
virtual const_iterator begin() const { return data; }
};
#define DEMO_MAX 256
template <size_t PIVOT=DEMO_MAX/2, size_t MIN=0, size_t MAX=DEMO_MAX>
struct factory
/* this does a binary search in a range of static types
*
* due to the binary search, this will require at most 2log(MAX) levels of
* recursions.
*
* If the parameter (size_t n) is a compile time constant expression,
* together with automatic inlining, the compiler will be able to optimize
* this all the way to simply returning
*
* new static_array<n>()
*
* TODO static assert MIN<=PIVOT<=MAX
*/
{
inline static iarray* instantiate(size_t n)
{
if (n>MAX || n<MIN)
throw std::range_error("unsupported size");
if (n==PIVOT)
return new static_array<PIVOT>();
if (n>PIVOT)
return factory<(PIVOT + (MAX-PIVOT+1)/2), PIVOT+1, MAX>::instantiate(n);
else
return factory<(PIVOT - (PIVOT-MIN+1)/2), MIN, PIVOT-1>::instantiate(n);
}
};
iarray* make_dynamic_array(size_t n)
{
return factory<>::instantiate(n);
}
void exercise(iarray& arr)
{
int gen = 0;
for (iarray::iterator it=arr.begin(); it!=arr.end(); ++it)
*it = (gen+=arr.size());
std::cout << "size " << arr.size() << ":\t";
std::copy(arr.begin(), arr.end(), std::ostream_iterator<int>(std::cout, ","));
std::cout << std::endl;
}
int main()
{
{ // boring, oldfashioned method
static_array<5> i5;
static_array<17> i17;
exercise(i5);
exercise(i17);
}
{ // exciting, newfangled, useless method
for (int n=0; n<=DEMO_MAX; ++n)
{
std::auto_ptr<iarray> dyn(make_dynamic_array(n));
exercise(*dyn);
}
try { make_dynamic_array(-1); } catch (std::range_error e) { std::cout << "range error OK" << std::endl; }
try { make_dynamic_array(DEMO_MAX + 1); } catch (std::range_error e) { std::cout << "range error OK" << std::endl; }
return 0;
srand(123);
for (int i=0; i<10; i++)
{
size_t N = rand() % DEMO_MAX; // capped for demo purposes
std::auto_ptr<iarray> dyn(make_dynamic_array(N));
exercise(*dyn);
}
}
return 0;
}
Declare it as:
int* array;
Then you can initialize it this way:
MyArrayOfInts::MyArrayOfInts(int length) {
this->array = new int[length];
}
Don't forget to free the memory in the destrutor:
MyArrayOfInts::~MyArrayOfInts() {
delete [] this->array;
}
Is the class declaration complete ? If the constructor of the class takes the size of the array as an argument and you don't want to resize the array, then templatizing the class can give you runtime behaviour.
Now, we don't have to pass the size of the array as argument to the constructor.
template<size_t size>
class MyClass
{
public:
MyClass() { std::iota(arr_m, arr_m + size, 1); }
int operator[](int index) const
{
return arr_m[index];
}
int& operator[](int index)
{
return arr_m[index];
}
void Set(size_t index, int value)
{
arr_m[index] = value;
}
private:
int arr_m[size];
};
int main()
{
{
MyClass<5> obj;
std::cout << obj[4] << std::endl;
}
{
MyClass<4> obj;
std::cout << obj[3] << std::endl;
obj.Set(3, 30);
std::cout << obj[3] << std::endl;
}
}
In response to critics in the comments
I think many people fail to notice a crucial given in the question: since the question asks specifically how to declare an int[N] array inside a struct, it follows that each N will yield a distinct static type to the compiler.
As much as my approach is being 'critiqued' for this property, I did not invent it: it is a requirement from the original question. I can join the chorus saying: "just don't" or "impossible" but as a curious engineer I feel I'm often more helped by defining the boundaries of ust what is in fact still possible.
I'll take a moment to come up with a sketch of an answer to mainly UncleBen interesting challenge. Of course I could hand-waive 'just use template metaprogramming' but it sure would be more convincing and fun to come up with a sample1
1 only to follow that sample with a big warning: don't do this in actual life :)
The TR1 (or c++0x) type std::array does exactly that; you'll need to make the containing class generic to cater for the array size:
template <size_t N> struct MyArrayOfInts : MyArrayOfIntsBase /* for polymorphism */
{
std::array<int, N> _data;
explicit MyArrayOfInts(const int data[N])
{
std::copy(data, data+N, _data);
}
};
You can make the thing easier to work with by doing a smart template overloaded factory:
template <size_t N>
MyArrayOfInts<N> MakeMyArray(const int (&data)[N])
{ return MyArrayOfInts<N>(data); }
I'm working on this too for solving a dynamic array problem - I found the answer provided was sufficient to resolve.
This is tricky because arrays in functions from my reading do not continue after function ends, arrays have a lot of strange nuance, however if trying to make a dynamic array without being allowed to use a vector, I believe this is the best approach..
Other approaches such as calling new and delete upon the same pointed to array can/will lead to double free pending the compiler as it causes some undefined behavior.
class arrayObject
{
public:
arrayObject();
~arrayObject();
int createArray(int firstArray[]);
void getSize();
void getValue();
void deleting();
// private:
int *array;
int size;
int counter;
int number;
};
arrayObject::arrayObject()
{
this->array = new int[size];
}
arrayObject::~arrayObject()
{
delete [] this->array;
}