类实例的地址是否等于类中唯一元素的地址

Is the address of an class instance equal with the address of the unique element in the class

本文关键字:地址 唯一 元素 于类中 是否 实例      更新时间:2023-10-16

我正在研究一段用 g++-7.4 编译的 C+ 代码 我的问题是,从类 B 返回类成员的地址是否安全,并将其分配为类 A 的指针,其中该成员是唯一的。 让我们用下面的例子来弄清楚

#include "pch.h"
#include <iostream>
class DummyMsg
{
public:
DummyMsg () = default;
DummyMsg(const DummyMsg &) = default;
~DummyMsg()=default;
};
class ROCallContext
{
public:
ROCallContext() = default;
ROCallContext(const ROCallContext &) = default;
~ROCallContext() = default;
DummyMsg *dummyMsg;
};
class RWCallContext
{
public:
RWCallContext()
{
dummyMsg = new DummyMsg();
}
~RWCallContext()
{
}
void* getDummyMsg()
{
return reinterpret_cast<void *>(dummyMsg);
}
int i;
double d;
char * pc;
DummyMsg *dummyMsg;
char c_array[100];
};
int main()
{
RWCallContext * rwCallContext = new RWCallContext();
ROCallContext * ctx = reinterpret_cast<ROCallContext *>(rwCallContext->getDummyMsg());
}

ROCallContext::d ummyMsg是否等于 RWCallContext::d ummyMsg? ROCallContext::d ummyMsg 的内容是否与 RWCallContext::d ummyMsg 的内容相同?

是否取决于编译器优化?

这将是一个真正的成功或失败,因为你的问题有点模糊。

传递指针是否安全......是的,当然,如果你跟踪它,当代码变大时,你可能无法做到这一点。如果您需要传递指针,请改用shared_ptr。

无论如何,如果你运行这段代码,它有望解释你的第二个问题,如果指针相等。希望这对你有意义。

#include <iostream>
class DummyMsg {
public:
int i = 0;
};
class ROCallContext {
public:
ROCallContext(DummyMsg *msg) {
dummyMsg = msg;
}
DummyMsg *dummyMsg;
};
class RWCallContext {
public:
RWCallContext() {
dummyMsg = new DummyMsg();
}
DummyMsg* getDummyMsg() { 
return dummyMsg;
}
DummyMsg *dummyMsg;
};
int main() {
RWCallContext * rwCallContext = new RWCallContext();
ROCallContext * ctx = new ROCallContext(rwCallContext->getDummyMsg());
printf("Address of RW is %pn", (void *)rwCallContext->dummyMsg);
printf("Address of RO is %pn", (void *)ctx->dummyMsg);
printf("RO i: %in", ctx->dummyMsg->i);
printf("RW i: %in", rwCallContext->dummyMsg->i);
printf("Changing value for RWn");
rwCallContext->dummyMsg->i = 2;
printf("RO i: %in", ctx->dummyMsg->i);
printf("RW i: %in", rwCallContext->dummyMsg->i);
delete rwCallContext->dummyMsg;
delete rwCallContext;
delete ctx;
}

编辑:刚刚意识到问题可能是 dummyMsg 是否是相同的值,即使您从/放入的类没有相同的结构。 如果是这种情况,也许这个例子解释了为什么它可能没有相同的值。

#include <stdio.h>
struct A {
int x;
int y;
};
struct B {
int y;
int x;
};
int main() {
struct A a = {1, 2};
struct B *b = (struct B*)&a;
printf("Struct A x: %i, y: %in", a.x, a.y);
printf("Struct B x: %i, y: %in", b->x, b->y);
}
Output:
Struct A x: 1, y: 2
Struct B x: 2, y: 1