调用 ctor/dtor 中已删除的函数“addressof”

克里斯

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是一个纯右值表达式

std::addressof

template <class T>
const T* addressof(const T&&) = delete;

因此addressof删除了右值的重载。原因是因为您无法获取纯右值的地址,因此addressof建模以尊重这一点。

这就是您收到错误的原因。


请注意,addressof(this)(void*) this甚至不在同一个球场上。相当于addressof(this)将是&thiswhich 也不能编译。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章