Here is my code:
template<typename B>
class cvector{
public:
cvector(){
allocatedSize =0;
actualSize = 0;
buffer = 0;
}
cvector(int k):allocatedSize(k){
}
cvector(int k, const B& initial ):allocatedSize(k), actualSize(k){
buffer = new B[allocatedSize];
for(int i = 0;i<allocatedSize;i++){
buffer[i] = initial;
}
}
~cvector(){
delete [] buffer;
}
private:
int allocatedSize;
int actualSize;
B* buffer;
};
int main(int argc, char** argv) {
cvector<int> pee(2,int(5));
cvector<int*> kay(2,new int(10));
return 0;
}
I am trying to emulate std::vector
. My code isn't optimized and clean yet as this is just a draft but as of now, i get no problems and here are my test cases when initializing:
cvector<int> p(2,int(5)); //no error
cvector<int*> k(2,new int(10)); //no error
cvector<int> j(2,new int(5)); // error because it's int
cvector<int*> l(2,int(2)); //error because it's a pointer
I am curious how are these B
expressions evaluated if i will put int
or int*
?
B* buffer; // (int*)* so int *? (just like reference collapsing?
buffer = new B[allocatedSize]; // new int* if int* ?!
So if i wil use int*
then B* buffer;
will be int*
? what about buffer = new B[allocatedSize];
and const B& initial
from my code?
"Pointer collapsing" doesn´t exist.
No stars will be added or removed or anything else.
B* buffer;
buffer = new B[allocatedSize];
with B being int
results in
int* buffer;
buffer = new int[allocatedSize];
ie. an array of int
, and you can do whatever you want with the int
´s.
With B being int*
, it will be
int** buffer;
buffer = new int*[allocatedSize];
ie. an array of int pointers, all pointers pointing nowhere (initially),
and you can do whatever you want with your pointers.
how are these B expressions evaluated if i will put int or int* ?
For int
, the B
will be int*
and for int*
, the B
will be int**
.
So if i wil use int* then B* buffer; will be int* ? what about buffer = new B[allocatedSize]; and
const B& initial
from my code?
No. B*
will be int**
as mentioned above. For int*
the expression would look like:
(int**)buffer = new int*[allocatedSize];
The const B& initial
would be evaluated as const int*&
.
With my advice, for the production code you may think above having std::vector
as an object and cvector
as a wrapper around it. Or inherit cvector
from std::vector
in a kind of "has a" relationship.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.