当我取消引用一个指针并分配给它时,它会更改指针指向的内容,它不会为它指向的内容调用 operator=
。我做了这个程序来证明这一点:
#include <iostream>
struct S
{
void operator =(int)
{ x = 5; }
operator int*()
{
return &x;
}
int x;
};
std::ostream& operator <<(std::ostream& out, S const& s)
{
return out << s.x;
}
int main()
{
S s;
int *x = s;
*x = 10;
std::cout << *x;
}
这会打印 10。执行 *x = 10
不会修改 x
指向的对象。我怎样才能让它这样做? (欢迎使用 C++11 解决方案)
最佳答案
您的代码是未定义的行为。 int *x = S();
将 x
初始化为一个临时地址,它在完整表达式的末尾被销毁,所以 *x
是非法的。
关于c++ - 如何使指针的取消引用保留对该对象的引用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16907834/