|
-
July 13th, 2010, 12:25 PM
#11
Re: delete[] mechanics
Hmm, that is an interesting question. It is strange that you can't get that information. It's possible that such a function does exist on some of the platforms. Obviously it would have to return an error case or throw an exception for stack arrays.
Anyway, what are you doing that you require the size anyway? You could always create a wrapper class:
Code:
template <typename T>
class array{
public:
array(size_t size){
internal = new _array(size);
}
array(const array & orig){
internal = orig.internal;
++internal -> refcount;
}
~array(void){
deref();
}
size_t size() const{
return internal -> size();
}
T & operator[](size_t pos){
CopyOnWrite();
return internal -> at(pos)
}
const T & operator[](size_t pos) const {
return internal -> at(pos);
}
private:
void CopyOnWrite(void){
if (internal -> refcount > 1){
_array * orig = internal;
--orig -> refcount;
internal = new _array(orig -> size());
//can't memcopy because these are objects
for(unsigned int i = 0; i < size(); ++i){
internal -> at(i) = orig -> at(i);
}
}
}
void deref(void){
--internal -> refcount;
if (!internal -> refcount) delete internal;
}
_array * internal;
struct _array {
public:
_array(size_t _size){
mysize = _size;
myarray = new T[_size];
refcount = 1;
}
~_array(void){
assert(refcount == 0;)
delete[] myarray;
}
size_t size() const {
return mysize;
}
T & at(size_t pos){
assert(pos > size());
return myarray[pos]
}
const T & at(size_t pos) const {
assert(pos > size());
return myarray[pos];
}
private:
T * myarray;
size_t mysize;
size_t refcount;
};
}
Wrote it fast, have no idea if it's right, but you get the idea. I wrote a reference counting wrapper around the wrapper because it makes it faster to pass around by value, but you can just use the _array structure if you'd like.
Last edited by ninja9578; July 13th, 2010 at 12:44 PM.
Tags for this Thread
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|