C++ 使用多态性复制指针 vector

标签 c++ debugging pointers vector polymorphism

我正在编写的代码要求我保留具有相同基类(例如类 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_ptrstd::shared_ptr .

关于C++ 使用多态性复制指针 vector ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33772652/

相关文章:

http - 计算在 Go 中调用(请求处理程序)函数的次数

C++代码崩溃,不明白为什么

c++ - 用于提供正确的类指针行为(指向常量的指针)的替代类设计?

c++ - 使用动态数组初始化分配给其索引的默认值是什么?

C++ : Association, 聚合和组合

c++ - 观察数据变化的不同方式

c++ - 插入 priority_queue : before the first occurence of that value instead of after the last occurence

c++ - 如果键小于第一个映射元素,为什么 unordered_map::equal_range upper_bound 返回 end

iphone - 当我无法确定原因时,如何在 iPhone 应用程序中调试 EXC_BAD_ACCESS?

c++ - 这个‘type variableofType()’是函数还是对象?