簡體   English   中英

在模板化類中折疊指針?

[英]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

我很好奇,如果我將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];怎么樣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表達式如何評估?

對於intB將為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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM