直到今天我才读到一些博客,我不知道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;
}发布于 2021-06-13 02:57:33
C++标准:
§9.3.2这个指针 关键字
this是prvalue表达式。
模板const T* addressof(const T&)=删除;
因此,rvalue的addressof重载被删除。原因是您无法获取prvalue的地址,因此对addressof进行建模以尊重它。
这就是为什么你会犯错误。
请注意,addressof(this)和(void*) this甚至不在同一范围内。相当于addressof(this)的是&this,它也不编译。
https://stackoverflow.com/questions/67954400
复制相似问题