这是我的代码:
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;
}
我正在尝试模拟 std::vector
。我的代码还没有优化和干净,因为这只是一个草稿,但到目前为止,我没有遇到任何问题,这是我在初始化时的测试用例:
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
我很好奇如果我将 int
或 int*
,这些 B
表达式是如何计算的?
B* buffer; // (int*)* so int *? (just like reference collapsing?
buffer = new B[allocatedSize]; // new int* if int* ?!
所以如果我要使用 int*
那么 B* buffer;
会是 int*
吗?
我的代码中的 buffer = new B[allocatedSize];
和 const B& initial
怎么样?
最佳答案
“指针折叠”不存在。
不会添加或删除任何星星或其他任何内容。
B* buffer;
buffer = new B[allocatedSize];
B 为 int
结果为
int* buffer;
buffer = new int[allocatedSize];
即。一个 int
数组,你可以用 int
做任何你想做的事。
如果 B 是 int*
,它将是
int** buffer;
buffer = new int*[allocatedSize];
即。一个 int 指针数组,所有指针都指向任何地方(最初),
你可以用你的指针做任何你想做的事。
关于c++ - 在模板类中折叠指针?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31227086/