C++ - vector<> 中的 std::unique_ptr 是 nullptr

C++ - std::unique_ptr in vector<> is nullptr

我想将 Particle 个对象存储在 vector 个对象中,以便稍后访问它。 这些粒子(ElectronsProtons)继承自 Particle class,其中包含一个 toString() 虚拟方法。此 toString() 方法随后在 ElectronProton classes.

中被覆盖

当我读取矢量容器时,我想访问特定于 ElectronProtontoString() 方法,而不是 Particle.

显然,一种方法是使用 std::unique_ptr。这是我尝试 运行:

的代码部分
int main(){
    /**/
    std::vector<std::unique_ptr<Particle>> particles(nbParticles);

    particles.push_back(std::unique_ptr<Electron>( new Electron(1.0, 2.0, 3.0)));
    particles.push_back(std::unique_ptr<Proton>(new Proton(1.0, 2.0, 3.0)));
    particles.push_back(std::unique_ptr<Particle>(new Particle(0.0, 0.0, 1.0, 2.0, 3.0)));

    if (particles[0]==nullptr){
        std::cout<< "index=0 : nullptr"<<std::endl; //There is a null_ptr at particles[0]
    }

    if (particles[2]==nullptr){
        std::cout<< "index=2 : nullptr"<<std::endl; //There is not a null_ptr at particles[2]
    }

    std::cout<<particles[0]->toString()<<std::endl; //This is what I'm trying to do
    /**/
}

指向 Particle 对象的指针似乎没问题,但指向 ElectronProton 的指针则不行。我想构造函数有问题吗?

class Particle
{
public:
    Particle();
    Particle(double mass, double charge, double posX, double posY, double posZ);
    virtual std::string toString() const;
}

class Electron : public Particle
{
public:
    Electron(double PosX, double PosY, double PosZ);
    virtual std::string toString() const;
}

class Proton : public Particle
{
public:
    Proton(double PosX, double PosY, double PosZ);
    virtual std::string toString() const;
}

和定义:

Particle::Particle(double mass, double charge, double posX, double posY, double posZ) :
    m_mass(mass), m_charge(charge),
    m_posX(posX), m_posY(posY), m_posZ(posZ) {}


Electron::Electron(double PosX, double PosY, double PosZ) :
    Particle(9.109E-31, -1.602E-19, PosX, PosY, PosZ){}

Proton::Proton(double PosX, double PosY, double PosZ) :
    Particle(9.109E-31, +1.602E-19, PosX, PosY, PosZ){}

您犯了一个经典的错误,即使是最有经验的 C++ 程序员也会犯错:您声明了具有初始大小的向量,然后 push_back 向其添加了其他元素,而不是分配给现有元素。通过从矢量初始化中删除 (nbParticles) 来解决此问题。