C++方法返回自身副本时内存泄漏
C++ memory leak when method returns a copy of itself
我有一个类似于下面的 c++ 代码。这将在Base::add
方法和total = &(*total + *to_add);
中产生内存泄漏。我该如何解决这个问题?
#include <iostream>
#include <string>
class Base
{
public:
int n;
Base(int input) : n(input) {}
Base(const Base& input)
{
n = input.n;
}
Base& add(Base &other, bool new_obj=true)
{
Base *self;
if (new_obj) {
self = new Base(other);
} else {
self = this;
}
self->n += other.n;
return *self;
}
Base& operator+=(Base &other)
{
return this->add(other, false);
}
};
Base& operator+(Base &self, Base &other)
{
return self.add(other);
}
class A : public Base
{
using Base::Base;
std::string print() {
return "Class A method_a";
}
};
class B : public Base
{
using Base::Base;
std::string print() {
return "Class B method_b";
}
};
int main()
{
Base *total = new Base(0);
for (int i=0; i<5; i++) {
Base *to_add = new A(i);
total = &(*total + *to_add);
}
for (int i=0; i<9; i++) {
Base *to_add = new B(i);
total = &(*total + *to_add);
}
return 0;
}
C++不是Java,你应该按值返回。从您的示例中不清楚派生类的用途,因此我假设您并不真正需要它们:
#include <iostream>
class Base
{
public:
int n;
Base(int input) : n(input) {}
Base(const Base& input) = default;
};
Base& operator+=(Base &x, const Base &y)
{
x.n += y.n;
return x;
}
Base operator+(const Base &x, const Base &y)
{
return Base(x.n + y.n);
}
int main()
{
Base total(0);
for (int i=0; i<5; i++) {
total += Base(i); // way 1
}
for (int i=0; i<9; i++) {
total = total + Base(i); // way 2
}
return 0;
}
total = &(*total + *to_add);
你为什么要这样对自己?total = (total + to_add)
不适合你吗?
在我看来,你好像试图在这里做矛盾的事情......
看起来你的 Base::add 函数是微不足道的,你可以按如下方式修改它:
Base& add(Base &other)
{
n += other.n;
return *this;
}
相关文章:
- 从构造函数抛出异常时如何克服内存泄漏
- malloc() 可能出现内存泄漏
- 这个极客对极客的trie实现是否存在内存泄漏问题
- 尽管遵循了规则,内存泄漏在哪里
- 为什么调用堆栈数组会导致内存泄漏
- 在简单示例中,Python3 + ctypes 回调会导致内存泄漏
- 使用模板类的自定义列表类型中的内存泄漏
- 为什么以下C++代码中存在内存泄漏?
- OpenCV 我应该使用智能指针来防止内存泄漏吗?
- 我是否生成线程并导致内存泄漏?
- 多线程程序中出现意外的内存泄漏
- 为什么此函数会导致内存泄漏?
- 在 C++ 库中使用cythonized python时内存泄漏
- 需要帮助查找内存泄漏
- 瓦尔格林德的内存泄漏使用新的
- 无法找出我的代码中的内存泄漏
- C++ 结构内部的unordered_map会导致内存泄漏问题吗?
- 可视化 使用 VS Code 查找C++应用程序中的内存泄漏
- Shared_ptr双链接列表内存泄漏
- C++ 在类中使用常量引用文本时 O2 内存泄漏