2014-05-02 182 views
1

我正在嘗試將動態足跡音頻合併到我的遊戲中。繼承人現在一些代碼:將unique_ptr矢量指定給矢量C++

class MyClass 
{ 
    vector< unique_ptr <Sound> > footstep_a; 
    vector< unique_ptr <Sound> > footstep_b; 
    vector< unique_ptr <Sound> > footstep_c; 
    vector<Sound> currentfootsteps; 
} 

所以基本上我想要做的就是分配footstep_載體之一currentfootsteps,這樣我可以再有:

if(walkingarea == a) 
    currentfootsteps = a; 
else ...... 

我試着做以下,但它只是拋出了關於向量和這樣的百萬錯誤:

if (walkingarea == a) 
    currentfootsteps.clear(); 
    for(int i = 0; i < footstep_a.size(); i++) 
     currentfootsteps.push_back(footstep_a[i]); 

誰能幫助我?

+0

您正將'std :: unique_ptr <>'推回到'Sound'對象的向量中。這就是你遇到錯誤的原因。 – 0x499602D2

回答

2

我真的不明白你想要做什麼,但假設Sound類是可複製,這將編譯:

currentfootsteps.clear(); 
for(auto const& up : footstep_a) { 
    currentfootsteps.push_back(*up); 
} 

注意,你正在做的每個元素的副本footstep_a並將其添加到currentfootsteps

如果Sound只有布展,或者你想避免拷貝,用這個來代替:

currentfootsteps.clear(); 
for(auto&& up : footstep_a) { 
    currentfootsteps.push_back(std::move(*up)); 
} 

但它也似乎你應該能夠通過使currentfootsteps一個指針,簡單的指向,以避免這一切取決於滿足的任何條件,到vector之一。

currentfootsteps.push_back(footstep_a[i]); 

您可以嘗試以獲得原始指針與.get()然後把它變成currentfootsteps:

vector< unique_ptr <Sound> > *currentfootsteps = nullptr; 

if (walkingarea == a) { 
    currentfootsteps = &footstep_a; 
} else if ... 
+0

非常感謝。完全沒有考慮使用你最後的建議lmao。你多愚蠢可以得到哈哈 – user2990037

1

正如其名sugguested,應該的unique_ptr被移動,而不是被複制。 同時,您需要確保Sound對象的使用期限足夠長。

因爲從我的理解,currentfootsteps僅保持參考這些Sound對象,而footstep_afootstep_bfootstep_c實際擁有它們。