0

Quite new to C++ here, i'm trying to create a bi-directional One-To-Many association between two classes.

Here's what i achieved so far :

class_a.h

#ifndef CLASS_A_H
#define CLASS_A_H

class ClassB;
class ClassA {
public:
   std::vector<ClassB *> Bs;
};

#endif

class_b.h

#ifndef CLASS_B_H
#define CLASS_B_H

class ClassA;
class ClassB {
public:
   ClassA *classA;
   std::string name;
};

#endif

But, when testing the following code, output is showing me test.

Is b being deleted correctly ? Should not this code returns a 139 error ?

main.cpp

auto *a = new ClassA();
auto *b = new ClassB();

b->classA = a;
b->name = "test";

delete b;

std::cout << b->name << std::endl;

Thanks !

Manu
  • 425
  • 4
  • 10

1 Answers1

4
delete b;

Once you delete b, it (and any other reference/pointer/iterator pointing to the same object) becomes invalid.

The behaviour of indirecting through an invalid pointer to access a member is undefined.

std::cout << b->name << std::endl;

Here, you indirect through an invalid pointer to access a member. The behaviour of the program is undefined.

Is b being deleted correctly ?

I see no evidence to the contrary.

Should not this code returns a 139 error ?

I don't know what a 139 error is but no, C++ does not guarantee such error to be returned. Nothing is guaranteed when the behaviour is undefined.

eerorika
  • 232,697
  • 12
  • 197
  • 326
  • 139 is probably the exit code in the shell, which corresponds to SIGSEGV aka segmentation fault. – bgfvdu3w Oct 16 '19 at 00:10
  • 1
    Yes, according to the C++ standard, it is [undefined behavior](https://en.wikipedia.org/wiki/Undefined_behavior). But just to explain what is probably happening: After calling `delete`, the heap manager will consider the memory to be free, meaning that the memory can be reassigned to some other memory allocation. Therefore, it is likely to be overwritten sometime in the future. However, that has not happened yet, so dereferencing the memory still gives you the old value. However, this is all speculation and cannot be replied upon, hence the term undefined behavior. – Andreas Wenzel Oct 16 '19 at 00:12
  • Got it. Thanks for your replies ! In fact, as the shell wasn't returning any error after running this snippet, i was afraid that there could be a memory leak. – Manu Oct 16 '19 at 00:52
  • @Manu Well, you do have a leak since you never delete `a`. You can use a tool such as valgrind to detect memory leaks, or a leak sanitiser that may be built into your compiler. – eerorika Oct 16 '19 at 00:55
  • Oh exactly, didn't even saw that ! Thanks again ! – Manu Oct 16 '19 at 01:06
  • 139 is [probably a segmentation fault](https://stackoverflow.com/a/15600683/10957435). –  Oct 16 '19 at 01:50