微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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!

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

原文地址:https://www.jb51.cc/c/116857.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐