c – 为什么两个不同对象的地址应该不同?

我一直在读这个东西,一个对象的大小至少应该是1个字节( C++: What is the size of an object of an empty class?),并且有两个空对象是同一个地址有什么不对?毕竟,我们可以有两个指向同一个对象的指针.

谷歌搜索告诉我有一些关于对象身份fundemantal规则,但我找不到更详细的信息.

所以… $SUBJ.

解决方法

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

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

是应该在o1还是o2上调用foo方法

可以认为,由于这些对象没有数据而没有虚拟方法(否则它们的大小非为零),调用方法的实例并不重要.但是,当我们想要测试两个对象是否相等时(即它们是否相同),这变得更加重要:

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!

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

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!

所以是的,这一切都归结为对象身份:如果允许对象为空,则可能会剥夺他们的身份,而这种语言根本不允许(谢天谢地).

相关文章

本程序的编译和运行环境如下(如果有运行方面的问题欢迎在评...
水了一学期的院选修,万万没想到期末考试还有比较硬核的编程...
补充一下,先前文章末尾给出的下载链接的完整代码含有部分C&...
思路如标题所说采用模N取余法,难点是这个除法过程如何实现。...
本篇博客有更新!!!更新后效果图如下: 文章末尾的完整代码...
刚开始学习模块化程序设计时,估计大家都被形参和实参搞迷糊...