Dora-SSR
Dora-SSR copied to clipboard
OwnVector使用方法请教
作者你好 在学习你的代码过程中,有个代码问题有点疑问,OwnVector这个模板类的remove方法的不太清楚要怎么调用.
/** @brief vector of pointers, but accessed as values
pointers pushed into OwnVector are owned by the vector,
pointers will be auto deleted when it`s erased/removed from the vector
or the vector is destroyed.
Used with Composition Relationship.
*/
template<class T>
class OwnVector : public vector<Own<T>>
{
typedef vector<Own<T>> OwnV;
public:
using OwnV::OwnV;
using OwnV::insert;
bool remove(T* item)
{
auto it = std::remove(OwnV::begin(), OwnV::end(), item);
if (it == OwnV::end()) return false;
OwnV::erase(it);
return true;
}
typename OwnV::iterator index(T* item)
{
return std::find(OwnV::begin(), OwnV::end(), item);
}
bool fast_remove(T* item)
{
size_t index = std::distance(OwnV::begin(), OwnVector::index(item));
if (index < OwnV::size())
{
OwnV::at(index) = OwnV::back();
OwnV::pop_back();
return true;
}
return false;
}
};
例子:
class demo{
public:
demo(int i):num(i){
cout<<"construct! " << i <<endl;
}
~demo(){
cout<<"class destruct! " << num <<endl;
}
private:
int num;
};
int main() {
OwnVector<demo> ov;
ov.push_back(New<demo>(1));
ov.push_back(New<demo>(2));
//ov.erase(ov.begin());
//ov.remove();
return 0;
}
比如这个例子中我想remove掉第一个item,应该怎么写呢?我在这个项目好像没有用到这个remove方法
抱歉,这个接口我没有做测试,这个原来模版接口的写法是不可用的……至少得改成这样你才能正常调用。
template<class T>
class OwnVector : public std::vector<Own<T>>
{
typedef std::vector<Own<T>> OwnV;
public:
using OwnV::OwnV;
using OwnV::insert;
bool remove(const Own<T>& item)
{
auto it = std::remove(OwnV::begin(), OwnV::end(), item);
if (it == OwnV::end()) return false;
OwnV::erase(it);
return true;
}
typename OwnV::iterator index(const Own<T>& item)
{
return std::find(OwnV::begin(), OwnV::end(), item);
}
bool fast_remove(const Own<T>& item)
{
size_t index = std::distance(OwnV::begin(), OwnVector::index(item));
if (index < OwnV::size())
{
OwnV::at(index) = OwnV::back();
OwnV::pop_back();
return true;
}
return false;
}
};
调用代码是这样:
class demo{
public:
demo(int i):num(i){
cout<<"construct! " << i <<endl;
}
~demo(){
cout<<"class destruct! " << num <<endl;
}
private:
int num;
};
int main() {
OwnVector<demo> ov;
ov.push_back(New<demo>(1));
ov.push_back(New<demo>(2));
ov.remove(ov[0]);
return 0;
}
这个类因为历史原因,是一个自己写的内存管理的容器,后来用标准库std::vector + std::unique_ptr做了替换,为了兼容临时改成这样。继承std标准库类的写法是不推荐的写法,因为自己很难保证自己写的子类也满足std的规范。后面会逐渐移除这些过渡代码。
好的,谢谢作者答疑