gpt4 book ai didi

c++ - 管理生命周期

转载 作者:行者123 更新时间:2023-11-28 00:53:52 24 4
gpt4 key购买 nike

我创建了一个容器来控制某些类型对象的生命周期(新建/删除)以避免任何编程错误。例如,一个对象在没有通知容器的情况下被删除。这些对象继承自相同的基类 (GreetingBase)。

对于实现,我使用了“模板技巧”:

class GreetingBase{
public:
virtual void sayHello(){
std::cout << "Hello there!" << endl;
}

virtual ~GreetingBase(){}
};

class GreetingDerived: public GreetingBase{
public:
virtual void sayHello(){
std::cout << "Hola amigos!" << endl;
}
virtual ~GreetingDerived(){}
};

class GreetingContainer{
public:
template <class T>
void addClass(){
items.push_back(new T());
}
~GreetingContainer(){
for(std::vector<GreetingBase*>::iterator it = items.begin();
it < items.end(); it++ ){
delete *it;
}
}

void talk(){
for(std::vector<GreetingBase*>::iterator it = items.begin();
it < items.end(); it++ ){
(*it)->sayHello();
}
}
private:
std::vector<GreetingBase*> items;
};


int main(){
GreetingContainer container;
container.addClass<GreetingDerived>();
container.talk();
return 0;
}

问题:

  1. 使用模板来解决这个问题是一种常见的方法吗?有什么缺点吗?
  2. 当“T”不是来自“GreetingBase”时报告更好的错误消息的任何“标准方法”

提前谢谢你。

最佳答案

Using templates in order to solve this problem is a common approach?

我不知道这是否普遍,但看起来足够明智。它确保您的容器只能包含指向使用 new 分配的对象的指针,这很好。

any drawbacks?

主要问题是您的容器破坏了 Rule of Three .它有一个隐式生成的复制构造函数和复制赋值运算符,可以简单地复制每个指针;这会给你两个容器对象,它们的析构函数都试图删除相同的对象。

解决这个问题的最简单方法是删除这些成员函数,或者如果您坚持使用该语言的 2011 之前版本,则将它们声明为私有(private)(没有实现)。如果您需要能够复制容器,则需要实现它们以安全地进行复制。

就个人而言,我会使用智能指针而不是滚动我自己的 RAII 容器; std::unique_ptr 如果容器拥有独占所有权,std::shared_ptr 如果您想共享所有权,或者可能是 std::weak_ptr 持有对共享指针在别处管理的对象的非拥有引用。如果您停留在过去,那么 unique_ptr 将不可用,但 Boost 提供了 shared_ptrweak_ptr 以及 Pointer containers和你的相似。

Any "standard way" to report better errors messages when "T" is not derived from "GreetingBase"

在 C++11 中,您也许可以使用静态断言,例如:

static_assert(std::is_base_of<GreetingBase, T>::value, 
"Wrong type for GreetingContainer");

或者,您可能会通过创建本地指针来获得更易读的错误消息;那么错误消息至少不会包含push_back的全名:

GreetingBase * p = new T();
items.push_back(p);

错误消息类似于can't convert Whatever* to GreetingBase*,应该很清楚了。

关于c++ - 管理生命周期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12580857/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com