Expression: _BLOCK_TYPE_IS_VALID(pHead->nBlockUse) Error

限于喜欢 提交于 2019-12-03 08:54:34
Ivan Aksamentov - Drop

Issue

void Event::set(Room r, const std::string& name) 
{
    d_room = &r;
    //      ^
    d_name = name;
}

You are referencing to the temporary object: Room r passed by value, which is destroyed at the end of the scope: }.

Instead you must reallocate the member pointer:

d_room = new Room(r);

Why it went wrong

Because you are writing C-style code in C++ classes.

In C++ we tend to:

  1. Avoid naked pointers, prefer smart pointers:

    class Event 
    {
        std::shared_ptr<Room> d_room;
     ...
    
    Event::~Event() { /* no need to delete */ }
    
  2. Use constructor overloading (instead of using set-like functions after construction):

    Event(Room& r, const std::string& name):
            d_room(new Room(r)),
            d_name(name)
    {}
    
  3. Pass by reference:

    void set(Room& r, const std::string& name);
    
  4. Avoid raw arrays, use STL facilities instead:

    std::vector<Event> lectures;
    // or
    std::array<Event, 5> lectures;
    

Another issue

r.d_hasProjector != r.d_hasProjector; // checks if r.d_hasProject is not itself

You probably want

r.d_hasProjector = !r.d_hasProjector;

Complete code: link

Also, here is a must-read link about advanced C++ stuff which, I believe, will be very useful to you: http://www.parashift.com/c++-faq/

Edit: I forgot about your question:

In addition to this, the printed text displays numbers that are very large and often negative. What is causing this?

Those numbers are garbage. Variables that are not explicitly initialized are not initialized at all. Memory is allocated but holds old information from previous program. It could contain anything. When you read from uninitialized variables, you'll get this garbage. You had a pointer which was pointing to a destroyed object. So the pointer was effectively uninitialized.

Your problem is here:

void Event::set(Room r, const std::string& name) {
    d_room = &r;
    d_name = name;
}

The &r takes the address of an object whose lifetime ends when the function returns, resulting in undefined behaviour when you later try to access it.

If you want to use pointers, you need to allocate them dynamically:

void Event::set(Room* r, const std::string& name) {
    d_room = r;
    d_name = name;
}

// ...
for (int i = 0; i < noLect; ++i) {
    Room* r = new Room;
    r->d_noSeat = i + 1;
    r->d_hasProjector != r.d_hasProjector;
    lectures[i].set(r, "CSI2372");
    lectures[i].print();
}
// ...

But it doesn't look like you need pointers here, you should be able to have

Room d_room;

in the Event class.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!