简体   繁体   中英

Why does pass by reference cause this to crash (C++)?

I'm experiencing some weird behavior and I'm not really sure where to turn.

Basically, I have a set of classes and one of them should be constructed with instances of the other two. I'm using pass by reference to assign the resources but the second assignment is crashing on my machine. I don't understand why the second assignment crashes but the first works fine. To make this a little more confusing, I tried recreating the problem in an online cpp compiler, but it seems to run fine in that environment.

I obscured the class names and removed a few methods that didn't seem relevant to this problem. Does anyone have any ideas?

#include <iostream>

using namespace std;

class Driver{};
class ITransmission{};
class ManualTransmission : public ITransmission {};

class Car
{
public:
    Car(ITransmission &trans, Driver &driver);

private:
    ITransmission *m_trans;
    Driver *m_driver;
};

Car::Car(ITransmission &trans, Driver &driver)
{
    *m_trans = trans;
    *m_driver = driver; // <-- **** Crashes here!?!? ****
}

int main()
{
    ITransmission *trans = new ManualTransmission();
    Driver *driver = new Driver();
    Car car(*trans, *driver);

    return 0;
}

*m_trans and *m_drivers are only pointers to their respective types. They are not the object themselves. In your copy constructor you are calling

*m_trans = trans

which crashes because m_trans doesn't point to anything and you are dereferencing it. What you want instead is,

m_trans = &trans
m_driver = &driver

This sets the pointer to point at the address of the object you've passed in, whereas before you were trying to assign to the pointed-to object.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM