检查传递给方法的对象是否"this"
Checking if the object passed to a method is "this"
我正试图解决以下问题:
假设我正在编写某个类,该类有一个方法myMethod
,它同时修改*this
和传递的参数:
class MyClass {
//some code here
void myMethod(MyClass& other) {
//modify *this and other
}
};
问题是,当调用以下部分时,我希望该方法什么都不做:
MyClass x;
x.myMethod(x);
仅仅检查相等是不够的,因为我希望能够为两个相同的对象调用它。
以一种更实际的方式,例如,假设MyClass
类似于std::set
,而myMethod
合并了两个集合,清空了other
。两个相同的集合可以合并,但我显然不能同时清空和填充一个集合。
我该怎么查?如有任何建议,我们将不胜感激。
您只需比较other
和this
:的地址
class MyClass {
//some code here
void myMethod(MyClass& other) {
if (this != &other) {
//modify *this and other
}
}
};
由于您是通过引用传递的,如果您将与您调用它的对象相同的对象传递给函数,则指针将相等。
您可以检查对象的地址。如果它们相同,返回或抛出异常或其他什么:
class MyClass {
//some code here
void myMethod(MyClass& other) {
if(this==&other){
//return or throw
}
//modify *this and other
}
};
这个简单的
If (&other == this)
.....your code......
您描述的这些困难类似于编写复制赋值运算符的困难。基本上,在使用完全性能优化的同时,单独的地址检查不足以在出现异常的情况下实现操作的完全正确性。您可以使用"复制并交换"习语中的思想来实现异常安全。
以下是代码示例:
void MyClass::foo(MyClass& other) {
MyClass tmp(this);
tmp.add_from(other);
other.empty();
swap(tmp, *this);
}
这里交换需要确保永远不会抛出异常。你仍然可以在一开始比较地址,但这只是一个性能优化,而不是实际的安全机制。
相关文章:
- 当一个新对象被分配到它的地址时,对象是否必须被销毁
- 在这种情况下,java对象是否可以调用本机函数
- 堆分配的对象是否存在永不为空的唯一所有者?
- QFileSystemModel 对象是否会被删除?
- 具有相同特征的两个对象是否只在内存中存储一次?无论定义它们的函数是什么,都是不同的
- 内联函数的函数本地静态对象是否在共享对象文件之间共享?
- 临时C++对象是否为左值?
- 为什么复制构造函数不需要检查输入对象是否指向自身?
- "this"指向的对象是否与 const 对象相同?
- 有什么方法可以检测我的类的对象是否在堆栈上创建
- 基类对象是否隐式添加到派生类中?
- 当 T 具有非平凡析构函数时,类类型 T 的对象是否可以常量初始化?
- 如何检查指针后面的对象是否有效或已删除?
- 谷神星求解器:残差函子使用的可变对象是否良好实践?还有什么其他选择
- 单一实例对象是否通过线程安全返回shared_ptr
- 对象是否保证在调用其成员函数之前被初始化
- 在另一个对象 B 中创建对象 A 时,对象 A 是否是对象 B 的本地对象,对象 A 是否会存在于对象 B 的实例化之外?
- 如何确定对象是否已分配成员
- 我们如何在c 中序列化或应对类的对象.是否有任何预定义的库
- 友元类对象是否可以在其成员函数中访问派生类对象的基类私有成员?