如何获得初始化器的地址
How can I get the address of initializer?
下面的代码引入了一个类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
指针),并且可以放置它找个你以后可以拿到的地方。我不建议这么做,但是,由于对象不会存在太长时间,因此您无法对其进行大量操作它。(另一方面,它有时对调试输出很有用它。)
相关文章:
- 初始化值是否保证通过其自己的地址反映,而不考虑内存顺序
- 使用成员的地址初始化基类是否合法?
- 如何使用构造函数初始化内存地址(指针变量)?
- 获取未初始化对象成员的地址是否定义良好?
- 为什么调用 cout.operator<<(const char*) 打印地址而不是字符串? 如何创建一个函数本地静态"HashSet<char>"并初始化它一次?
- 指向未由对象地址初始化的对象的指针如何将值分配给类的数据成员
- 在初始化期间,可以安全地将会员地址发送到父类
- 设置成员 GlobalCEFApp->OnWebKit使用函数地址初始化 C++生成器
- 初始化后相同的内存地址
- 初始化地址队列
- 给定内存地址的内存动态初始化
- 初始化整数成员变量会导致更改另一个成员变量的地址
- 使用地址值初始化指针
- 为什么我不能用 const int 的地址初始化 int*
- 通过写入全局llvm的地址从执行引擎外部初始化全局llvm值有效吗
- 初始化 malloc 地址中的类对象
- 初始化C++引用-为什么不使用运算符的地址
- 初始化指针而不给出地址
- 在c或c++中,如何区分在内存地址上设置的0和由于该地址未初始化而设置的0
- 如何用c++中另一个数组的地址初始化一个数组