我正在编写的代码要求我保留具有相同基类(例如类 Derived1
)的两种类型的对象(例如类 Derived2
和类 Base
)的集合。基类还有一个纯虚函数,该函数在这两个派生类中都有实现。
我使用指向基类对象的点 vector (即 vector<*Base> myCollection
)来跟踪所有这些对象。然而,我经常需要复制这个 vector 。
我尝试在基类中创建一个复制函数,以便我可以创建 Derived1
的其他实例。或Derived2
。但是,我注意到一些奇怪的行为。
以下是此行为的示例:
#include <iostream>
#include <vector>
#include <string>
using namespace std;
class A
{
public:
int member;
string name;
A(int x, string str = "Base"): member(x), name(str) {}
A* CreateCopy()
{
A tmp = A(member); // tmp: member = 77, name = "Base"
return &tmp; // &tmp: member = 77, name = ""
}
};
class B : public A
{
public:
B(int x) : A(x, "Derived Class") {}
};
int main()
{
A* ptr = &B(77); // &tmp: member = 77, name = ""
B test(77); // test: member = 77, name = "Derived Class"
A* ptr2 = &test; // *ptr2: member = 77, name = "Derived Class"
A* newPtr = ptr->CreateCopy(); // *newPtr: member = 77, name = ""
return 0;
}
当我创建一个对象时B
并将对象的引用分配在同一行上,我失去了名称成员的正确性。但是,当我创建该对象,然后分配它的引用时,它就起作用了。不幸的是我的 CreateCopy()
也遇到同样的问题方法。
这里发生了什么,复制指针 vector 的最佳方法是什么?是否可以在不使用 new
的情况下执行复制运算符(operator)?看来使用此运算符时更容易发生内存泄漏。
最佳答案
对于A* ptr = &B(77);
,B(77)
是一个临时对象,表达式完成后将被销毁,然后 ptr
将成为悬空指针。
对于
A* CreateCopy()
{
A tmp = A(member); // tmp: member = 77, name = "Base"
return &tmp; // &tmp: member = 77, name = ""
}
tmp
是一个局部变量,当超出函数范围时将被销毁,这意味着 CreateCopy()
将返回一个悬挂指针。
Is it possible to perform the copy without using the "new" operator? It seems like memory leaks are more likely to happen while using this operator.
您可以使用智能指针来避免手动内存管理。如std::unique_ptr或std::shared_ptr .
关于C++ 使用多态性复制指针 vector ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33772652/