简体   繁体   English

内存在C ++中共享吗?

[英]Memory is being shared in C++?

Can someone explain to me how data is being utilized since I was messing around with the following code...: 自从我弄乱了以下代码以来,有人可以向我解释如何利用数据...:

#include <stdio.h>
#include <stdlib.h>

typedef struct MyStruct {
public:
    void print() {
        printf("MyStruct.print():\n\ta: %i\n\tb: %i\n\n", a, b);
    }
    void store() {
        a = 2;
        b = 3;
    }
private:
    int a, b;
};

typedef struct MyStruct2 {
public:
    void print() {
        printf("MyStruct2.print():\na: %i\nb: %i\n\n", a, b);
    }
    void store() {
        a = 1024;
        b = 3077;
    }
private:
    int a, b;
};

int main() {
    void *ptr = malloc(sizeof(MyStruct)); // sizeof(MyStruct) == sizeof(MyStruct2)
MyStruct* pstruct = (MyStruct*)ptr;

pstruct->store();
pstruct->print();

MyStruct2* pstruct2 = (MyStruct2*)ptr;

pstruct2->store();
pstruct->print();

return 0;
}

and I got the following results: 我得到以下结果:

MyStruct.print():
        a: 2
        b: 3

MyStruct.print():
        a: 1024
        b: 3077

As you can see I didn't allocate any more memory for the pstruct2, yet I was able to access it. 如您所见,我没有为pstruct2分配更多的内存,但是我能够访问它。 Can anyone explain to me, or at least give me a reference/tutorial to something that is close to this that explains it. 任何人都可以向我解释一下,或者至少给我一份与之接近的解释/参考/指南。

Both pstruct and pstruct2 point to the same location in memory (Since you assigned the address stored in ptr to both) and thus the data inserted by the MyStruct::store method was overwritten by the MyStruct2::store method. pstructpstruct2指向存储器中的相同的位置(由于您分配存储在地址ptr两者),从而由所述插入的数据MyStruct::store方法是由覆盖MyStruct2::store方法。

In other words, this is happening because you are explicitly making it happen. 换句话说,这是因为您明确地使之成为现实。 If your two classes weren't identical or if the compiler had produced different memory layouts of them, you would've possibly read out garbage data. 如果您的两个类不相同,或者编译器产生了不同的内存布局,则可能会读取垃圾数据。


Basically, C++ allows you to write into any dynamically allocated memory as much as you want, happily ignorant and oblivious of the fact that you had previously used this memory for another object. 基本上,C ++允许您根据需要写入任意动态分配的内存,愉快地无知并且忽略了您之前曾将该内存用于另一个对象的事实。

Undefined behaviour, which happens to successfully pretend it works. 未定义的行为,恰好成功地假装它起作用。

3.10 Lvalues and rvalues [basic.lval] 3.10左值和右值[basic.lval]

... ...

10 If a program attempts to access the stored value of an object through a glvalue of other than one of the following types the behavior is undefined: 10如果程序尝试通过以下类型之一以外的glvalue访问对象的存储值,则行为未定义:

— the dynamic type of the object —对象的动态类型

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

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