push_back是否会更改存储在其向量中的类型的结构?

问题描述

我有以下2个课程:

npx create-react-app my-app

class Core 
{
public:
    Core() : mid(0),fin(0) {}
    Core(std::istream &in)
    {
        read(in);
    }
    virtual ~Core() {}
    Str name() const
    {
        return n;
    }
    virtual double grade() const
    {
        return vec_grade(mid,fin,hws);
    }
    virtual std::istream &read(std::istream &in);

protected:
    std::istream &read_common(std::istream &in);
    double mid,fin;
    Vec<double> hws;
    virtual Core *clone() const
    {
        return new Core(*this);
    }

private:
    friend class Student2;
    Str n;
};

std::istream &Core::read_common(std::istream &in)
{
    in >> n >> mid >> fin;
    return in;
}

std::istream &Core::read(std::istream &in)
{
    read_common(in);
    read_vec(in,hws);
    return in;
}

现在的问题是这样:

class Student2
{
    Core *cp;

public:
    Student2() : cp(0) {}
    Student2(std::istream &in) : cp(0)
    {
        read(in);
    }
    Student2(const Student2 &s) : cp(0)
    {
        if (s.cp)
            s.cp->clone();
    }
    Student2 &operator=(const Student2 &s);
    ~Student2()
    {
        delete cp;
    }
    std::istream &read(std::istream &in);
    Str name() const
    {
        if (cp)
            return cp->name();
        else
            throw std::runtime_error("uninitialized Student");
    }
    double grade() const
    {
        if (cp)
            return cp->grade();
        else
            throw std::runtime_error("uninitialized Student");
    }
    static bool compare(const Student2 &x,const Student2 &y)
    {
        return x.name() < y.name();
    }
    Core *getPointer() const
    {
        return cp;
    }
};

std::istream &Student2::read(std::istream &in)
{
    delete cp;
    char ch;
    in >> ch;
    if (ch == 'U')
    {
        cp = new Core(in);
    }
    else
    {
        cp = new Grad(in);
    }
    return in;
}

输出

int main()
{
    vector<Student2> v;
    Student2 s(cin);
    v.push_back(s);
    printf("%p\n%p\n",s.getPointer(),v[0].getPointer());
}

在这里我被读入对象0x562fa03b9280 (nil) ,该对象将具有其地址。但是一旦我通过Student2将其添加到向量中,相同的 objetc就会以某种方式丢失(将得到空指针)其地址。我不知道push_back是如何修改其值的,但是不应该这样做(因为否则它将获得其值)。 push_back的值是什么?

解决方法

它使用您编写的复制构造函数。这个:

Student2(const Student2 &s) : cp(0)
{
    if (s.cp)
        s.cp->clone();
}

cp设置为null(0)。这就是副本的cp为空的原因。

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...