c++ - 在模板类中折叠指针?

标签 c++ vector

这是我的代码:

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

我很好奇如果我将 intint* ,这些 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/

相关文章:

c++ - HashMap : What's the difference between a node map and a flat map?

c++ - 反转 for 循环...想要反向打印数字

mysql - 在 MySQL 中存储 Vector3

c++ - 如何使用 Boost 库比较两个不同的日期?

c++ - 模板类中没有名为 X 的类模板

c++ - 插入一个元素到柠檬图库 map 而不复制

c++ - 使用 vector<char> 实现串行缓冲区的最佳方法是什么?

c++ - 二维 vector - 查找重复元素/获取索引位置并计算重复项

c++ - 使用 std::vector 和内存释放

math - 给定一个轴的向量,如何找到其他两个轴的向量?