[英]What happen to pointer members of a class if I assign a rvalue to an object of that?
在B = B.foo()行之后,我对Ba的值应该有什么期望? ?
我期望Ba = 44,但我得到Ba = 0。 那有道理吗?
class A { //here is a class A
public:
int *a;
A(){ a = new int; *a=22;}
A foo(){ A anA; //anA is an object of the class A
*anA.a=44;
return anA;
}
~A(){ delete a;}
};
int main(){
A B;
B=B.foo();
//What is the value of B.a at this line of the code
}
问题是您尚未为A
定义复制构造函数/赋值运算符,并且由于对B
的赋值至少调用了赋值运算符(在这种情况下,默认值是由编译器生成的),因此它只是从A中复制了a
指针。返回'A'实例,然后删除该实例时,内存将释放,并且B
a
成员现在指向垃圾。 如果添加一些日志记录,很容易看到:
#include <cstdio>
class A
{
public:
int *a;
A()
{
a = new int;
printf("A::A(0x%p): a is 0x%p\n", this, a);
*a = 22;
}
A foo()
{
A anA;
*anA.a = 44;
return anA;
}
~A()
{
printf("A::~A(0x%p): a is 0x%p\n", this, a);
delete a;
}
};
int main(int argc, char** argv)
{
A B;
B = B.foo();
}
输出:
因此,要么实现适当的复制构造函数/赋值运算符,要么将其中之一/全部删除,以在使用原始指针时避免复制。 例如,添加A(const A&) = delete;
和A& operator=(const A&) = delete;
将使您的程序无法编译,然后您就可以开始研究如何接近要进行复制的地方。
这里最大的问题是语义。 一种“使这项工作可行”的可能方法是:
#include <cstdio>
class A
{
public:
int *a;
A()
{
a = new int;
printf("A::A()(0x%p): a is 0x%p\n", this, a);
*a = 22;
}
A(const A& otherA)
{
a = new int;
printf("A::A(const A& otherA)(0x%p): a is 0x%p\n", this, a);
*a = *otherA.a;
}
A& operator=(const A& otherA)
{
printf("A::operator=(const A& otherA)(0x%p)\n", this);
// What are the semantics here? Transfer ownership? Copy Value?
*a = *otherA.a;
return *this;
}
A foo()
{
A anA;
*anA.a = 44;
return anA;
}
~A()
{
printf("A::~A(0x%p): a is 0x%p\n", this, a);
delete a;
}
};
int main(int argc, char** argv)
{
{
A B;
B = B.foo();
printf("B.a is %d\n", *B.a);
}
return 0;
}
但是,这里有一个问题-复制操作的语义是什么? 转移指针的所有权? 复制值? 由于编译器无法回答这些问题,因此仅复制成员。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.