如何获得初始化器的地址

How can I get the address of initializer?

本文关键字:地址 初始化 何获得      更新时间:2023-10-16

下面的代码引入了一个类c。该类有构造函数、复制构造函数、操作符=和一个成员。我怎么能得到C(2)在函数main()中创建的对象的地址?

#include <iostream>
class C
{
public:
    int a;
    C(const C &other)
    {   
        std::cout << "Copy Constructor:" << a << std::endl;
    }   
    C(int a)
    {   
        this->a = a;
        std::cout << "Constructor:" << a << std::endl;
    }   
    C &operator=(const C &other)
    {   
        std::cout << "operator=:this.a = " << a << " | other.a = " << other.a << std::endl;
        a = other.a;
        return *this;
    }   
    ~C()
    {   
        std::cout << "Destructor:" << a << std::endl;
    }   
};
    int main()
    {
        C a(1);
        a = C(2);
    }

你不能。禁止你接受临时人员的地址。它们将很快超出作用域,给您留下一个无效的地址。

您可以使用辅助函数在对象超出作用域之前将地址写在某个地方:

template <typename T>
T const & store_possibly_invalid_address(T const & t, T const *& p)
{
    p = &t;
    return t;
}
int main()
{
    C a(1);
    C const * invalid_address;
    a = store_possibly_invalid_address(C(2), invalid_address);
    // The temporary is out of scope, but you can see where it was.
    // Don't dereference the pointer.
}

这可能是有教育意义的,可以发现编译器选择在哪里放置临时变量。但是,它在任何实际代码中都没有用处。

唯一的方法是在类内部进行一些协作;的构造函数有地址(this指针),并且可以放置它找个你以后可以拿到的地方。我不建议这么做,但是,由于对象不会存在太长时间,因此您无法对其进行大量操作它。(另一方面,它有时对调试输出很有用它。)