[英]Collapsing pointers inside a templated class?
这是我的代码:
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];
怎么样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指针数组,所有指针均无处指向(最初),
您可以使用指针做任何您想做的事情。
如果我将int或int *放在这些B表达式如何评估?
对于int
, B
将为int*
;对于int*
, B
将为int**
。
因此,如果我将使用int *,则使用B *缓冲区; 会是int *吗? 缓冲区= new B [allocatedSize]怎么样? 和我的代码中的
const B& initial
?
号B*
将int**
如上所述。 对于int*
,表达式如下所示:
(int**)buffer = new int*[allocatedSize];
const B& initial
将被评估为const int*&
。
根据我的建议,对于生产代码,您可能会在上面将std::vector
作为对象并将cvector
作为包装器作为对象。 或以一种“具有”关系从std::vector
继承cvector
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.