简体   繁体   English

C++ 双向 class 关联(使用前向声明)

[英]C++ Bi-directional class association (Using forward declaration)

Quite new to C++ here, i'm trying to create a bi-directional One-To-Many association between two classes. C++ 在这里相当新,我正在尝试在两个类之间创建一个双向的一对多关联。

Here's what i achieved so far:这是我到目前为止所取得的成就:

class_a.h class_a.h

#ifndef CLASS_A_H
#define CLASS_A_H

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

#endif

class_b.h 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 .但是,在测试以下代码时, output 显示我test

Is b being deleted correctly? b是否被正确删除? Should not this code returns a 139 error?此代码不应该返回 139 错误吗?

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 !谢谢 !

 delete b;

Once you delete b , it (and any other reference/pointer/iterator pointing to the same object) becomes invalid.一旦您删除b ,它(以及指向同一对象的任何其他引用/指针/迭代器)将变得无效。

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? b 是否被正确删除?

I see no evidence to the contrary.我没有看到相反的证据。

Should not this code returns a 139 error?此代码不应该返回 139 错误吗?

I don't know what a 139 error is but no, C++ does not guarantee such error to be returned.我不知道 139 错误是什么,但不知道,C++ 不保证返回此类错误。 Nothing is guaranteed when the behaviour is undefined.当行为未定义时,没有任何保证。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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