开发者

Get the address of class's object in C++?

Suppose I have a C++ class as follows:

class Point {
// imp开发者_开发问答lementing some operations
}

Then:

Point p1;
Point p2 = p1;

If I want to know the address of p2, then I can use &p2. But how can I get the address that p2 stores? Because p2 is not a pointer, so I cannot just use cout << p2;


What's wrong with the following:

cout << &p2;

As you say, p2 is not a pointer. Conceptually it is a block of data stored somewhere in memory. &p2 is the address of this block. When you do:

Point p2 = p1;

...that data is copied to the block 'labelled' p1.

But how can I get the address that p2 stores?

Unless you add a pointer member to the Point data structure, it doesn't store an address. As you said, it's not a pointer.

P.S. The hex stream operator might be useful too:

cout << hex << &p2 << endl;


By doing

Point p2 = p1;

you simply copy the values of p2 onto p1 (most likely). The memory is independent. If you did instead:

Point* p2 = &p1;

then p2 will be a pointer onto p1 (printing its value will give you the begining of the memory block, you could then try the sizeof to get the size of the block).


The accepted answer proposes the use of operator & to obtain the address of an object.

As of C++11, this solution does not work if the object class defines/overloads operator &.

In order to get the address of an object, from C++11, the template function std::addressof() should be used instead.

Point p1;
Point* p2 = std::addressof(p1);

http://www.cplusplus.com/reference/memory/addressof/

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜