2013-08-25 73 views
1

我是新來的智能指針,我正在碰到每個絆腳石的過程。麻煩構建shared_ptr

我有一個結構texture_t

struct texture_t 
{ 
    hash32_t hash; 
    uint32_t width; 
    uint32_t height; 
    uint32_t handle; 
}; 

當我嘗試使用此線這個結構的shared_ptr

auto texture_shared_ptr = std::make_shared<texture_t>(new texture_t()); 

我得到這個錯誤:

error C2664: 'mandala::texture_t::texture_t(const mandala::texture_t &)' : cannot convert parameter 1 from 'mandala::texture_t *' to 'const mandala::texture_t &' 

這個錯誤來自哪裏,我該如何避免它?

回答

2

你不應該通過new ed指針std::make_shared。你只需要傳遞一個參數就可以構造一個texture_t

+0

工程就像一個魅力,謝謝。看起來這些東西比我想象的要聰明! –

4

std::make_shared<T>(args...)的要點是分配一個T對象,該對象使用參數args...構建。這個操作背後的想法是,std::shared_ptr<T>概念維持兩個分配對象:

  1. 一個指向類型T
  2. 一條記錄,跟蹤當前參考對象的當前數量std::shared_pt<T>和數量std::weak_ptr<T>對象。

在構建std::shared_ptr<T>時,構造函數會執行第二次分配以構造其內部簿記的記錄。 std:make_shared<T>(args...)只做一次內存分配。

您看到的錯誤是嘗試使用mandala::texture_t*構造mandala::texture_t的結果,但唯一的一個參數構造函數mandala::texture_t具有複製構造函數。但是,該指針不符合複製構造函數的參數。