为什么两个不同对象的地址应该不同? [英] Why addresses of two different objects should be different?

查看:72
本文介绍了为什么两个不同对象的地址应该不同?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在阅读有关这些内容的内容,即对象的大小至少应为1个字节(

I've been reading about this stuff that size of an object should be at least 1 byte (C++: What is the size of an object of an empty class?) and what's wrong about having two empty objects the same address ? After all, we can have two pointers to the same object.

谷歌搜索告诉我关于对象身份基本规则的一些事情,但是我找不到关于它的更详细的信息.

The googling tells me there is something about object identity fundemantal rule, but I can't find more detailed info about that.

所以... $ SUBJ.

So... $SUBJ.

推荐答案

在同一地址具有两个对象意味着使用指针引用它们时将无法区分这两个对象.例如,在以下代码中:

Having two objects at the same address would mean that there would be no way to distinguish between these two objects when referencing them with pointers. For example, in the following code:

EmptyClass o1;
EmptyClass o2;

EmptyClass * po = &o;
po->foo();

应该在o1o2上调用foo方法吗?

Should the foo method be called on o1 or o2?

可以争论的是,由于这些对象没有数据,也没有虚拟方法(否则它们的大小将为非零),因此在哪个实例上调用该方法都没有关系.但是,当我们要测试两个对象是否相等(即它们是否相同)时,这变得尤为重要:

It could be argued that since these objects have no data and no virtual methods (otherwise they would have a non-zero size), it doesn't matter on which instance the method is invoked. However, this becomes more important when we want to test if two objects are equal (i.e. if they are the same):

template < typename T >
bool isSame( T const & t1, T const & t2 )
{
    return &t1 == &t2;
}

EmptyClass o1; // one object and...
EmptyClass o2; // ...a distinct object...

assert( ! isSame( o1, o2 ) ); // ...should not be one and same object!

对于一个更具体的例子,让我们假设我想将一些对象(我可以说是实体)与一些值相关联,比如说在一个关联容器中:

For a more concrete example, let's assume that I want to associate some objects (I could say entities) with some values, let's say in an associative container:

Person you;
Person me;

// You and I are two different persons
// (unless I have some dissociative identity disorder!)
// Person is a class with entity semantics (there is only one 'me', I can't make
// a copy of myself like I would do with integers or strings)

std::map< Person *, std::string > personToName;

personToName[&you] = "Andrew_Lvov";
personToName[&me]  = "Luc Touraille";
// Oh, bother! The program confused us to be the same person, so now you and I
// have the same name!

是的,这全都归结为对象身份:如果允许对象为空,则可能会剥夺它们的身份,这是语言所不允许的(非常感谢).

So yes, it all boils down to object identity: if objects were allowed to be empty, they could be deprived of their identity, which is simply not allowed by the language (thankfully).

这篇关于为什么两个不同对象的地址应该不同?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆