std::addressof
直到今天我读了一些博客,我才知道c++ 标准库中有可用的。在我的理解中,如果opeartor &
是重载,那么std::addressof
应该使用,否则没有必要使用std::addressof
,它应该等同于&
。
但是,只是尝试使用std::addressof
, 来验证它是否与 相同&
,我遇到了编译错误:“调用已删除的函数'addressof'”。不知道为什么。
这是演示此问题的最少代码:
#include <iostream>
#include <memory>
class Foo
{
public:
Foo(int _len): len(_len) {
if(len>0) {
data = new double[len];
}
// compile error: call to deleted function 'addressof'
std::cout << "Foo() " << std::addressof(this) << "/" << std::addressof(data) << std::endl;
}
~Foo() {
// compile ok
std::cout << "~Foo() " << (void*)this << "/" << (void*)data << std::endl;
// compile error: call to deleted function 'addressof'
std::cout << "~Foo() " << std::addressof(this) << "/" << std::addressof(data) << std::endl;
if (data!=nullptr) {
delete[] data;
}
}
private:
int len;
double* data;
};
int main() {
Foo(42);
return 0;
}
C++标准:
§9.3.2 this 指针
关键字
this
是一个纯右值表达式
template <class T> const T* addressof(const T&&) = delete;
因此addressof
删除了右值的重载。原因是因为您无法获取纯右值的地址,因此addressof
建模以尊重这一点。
这就是您收到错误的原因。
请注意,addressof(this)
和(void*) this
甚至不在同一个球场上。相当于addressof(this)
将是&this
which 也不能编译。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句