具有数字集C++的多态性中的内存泄漏
Memory leak in polymorphism with number sets C++
我现在正在学习C++多态性,老师希望我们使用基类number_t和派生类:integer_t、real_t 如果没有多态性,我会植入与以下非常相似的 这样,当有两个数字的和时,它不会改变所涉及的数字的值,而是返回一个新的值。 但是对于多态性,我必须返回一个指针,例如,这就是我要做的: 这里的问题是 由总和 有什么更好的方法吗?operator+
:real_t real_t::operator+(const integer_t& number) const
{
/* Sum operations of (real_t + integer_t) */
/* Create a new real with the result of the sum and return it */
return real_t(...);
}
number_t* real_t::operator+(const number_t* number) const
{
/* Sum operations of two numbers which will output a real_t (for example)*/
/* Create a new real with the result of the sum and return it */
/* The return value will be of the type of the biggest set, for example:
integer + real = real
complex + real = complex
*/
return new real_t(...);
}
new
运算符创建的内存不会被释放。在此操作中:d = (a + b) + c
(a+b)
分配的内存永远不会被释放。
返回智能指针:
unique_ptr<number_t> real_t::operator+(const number_t& number) const
{
/* Sum operations of two numbers which will output a real_t (for example)*/
/* Create a new real with the result of the sum and return it */
return make_unique<real_t>(...);
}
现在,中间值将自动释放。
- 多态性和功能结合
- 找不到成员对象:没有名为get_event()的成员,也处理多态性和向量
- 使用取消引用的指针的多态性会产生意外的结果.为什么?
- C++boost序列化多态性问题
- 如何查找哪个类对象位于数组的特定索引上(多态性)
- 如何在多线程中正确使用unique_ptr进行多态性?
- 具有智能指针的多态性
- 在 C++ 中在堆栈上创建实例时如何保持多态性?
- 继承/多态性 - 我是否被迫使用"protected"变量?
- C++ 多态性在代码::块 17.12 中不起作用
- C++ 泛型和多态性:这种模式可行吗?
- 为什么我们实际上需要运行时多态性?
- 如何在这个简单的最小示例中实现多态性?
- 使用连续内存实现多态性
- 如何为多态性中的指定类型分配内存
- 是否可以将多态性类存储在共享内存中
- 具有数字集C++的多态性中的内存泄漏
- 内存泄漏和多态性
- 使多态性在C++映射中工作,而不会发生内存泄漏
- 使用指示器的c++和Java之间SWIG多态性中的内存泄漏