首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >调用ctor/dtor中已删除的函数'addressof‘

调用ctor/dtor中已删除的函数'addressof‘
EN

Stack Overflow用户
提问于 2021-06-13 02:43:07
回答 1查看 170关注 0票数 0

直到今天我才读到一些博客,我不知道std::addressof在c++标准库中是可用的。根据我的理解,如果opeartor &被重载,那么应该使用std::addressof,否则不需要使用std::addressof,它应该等同于&

但是,只要尝试使用std::addressof来验证它是否与&相同,我就会遇到编译错误:“调用已删除的函数'addressof‘”。不知道为什么。

下面是演示这个问题的最小代码:

代码语言:javascript
复制
#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;
}
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2021-06-13 02:57:33

C++标准:

§9.3.2这个指针 关键字this是prvalue表达式。

std:地址

模板const T* addressof(const T&)=删除;

因此,rvalue的addressof重载被删除。原因是您无法获取prvalue的地址,因此对addressof进行建模以尊重它。

这就是为什么你会犯错误。

请注意,addressof(this)(void*) this甚至不在同一范围内。相当于addressof(this)的是&this,它也不编译。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/67954400

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档