2014-05-02 184 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实际拥有它们。