类实例的地址是否等于类中唯一元素的地址
Is the address of an class instance equal with the address of the unique element in the class
我正在研究一段用 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
相关文章:
- 将数组的地址分配给变量并删除
- 空基优化子对象的地址
- C++ 指针的内存地址和指向数组的内存地址如何相同?
- 何时在引用或唯一指针上使用移动语义
- C++优先级队列,按对象的唯一指针的特定方法升序排列
- 计算排序向量的向量中唯一值的计数
- 在C++中打印指向不同基元数据类型的指针的内存地址
- 如何使用Visual Studio 2017在C++中为参数化对象数组使用唯一指针
- 如何在c++程序中找到函数的地址
- 向量元素的引用地址与它所指向的向量元素的地址不同.为什么
- 被解释为低级别const的const对象的地址
- 将地址分配给本地指针后,公共对象的变量将消失
- 常量引用函数参数的地址何时唯一?
- 在C++中为零大小的分配返回唯一地址背后的基本原理是什么?
- 类实例的地址是否等于类中唯一元素的地址
- 获取系统的唯一标识符(而不是MAC地址)
- 一个IP地址和一个端口号可以一起唯一地标识一个进程ID吗
- vector中的每个元素是否都有唯一的内存地址?
- 为什么控制台在使用运算符的地址时只打印整数变量的1个唯一地址
- constexpr变量的唯一地址