为什么直接传递"this"指针来存档是一个错误,而另一个相同类型的指针是可以的?

Why is passing 'this' pointer directly to archive an error, but another pointer of same type is ok?

本文关键字:指针 错误 一个 另一个 同类型 this 为什么      更新时间:2023-10-16

传递分配给另一个指针的this指针工作正常,但直接传递它本身不会如下所示:

table_row* table_row::deserialize_row(std::string src_serialized_row) {
std::stringstream ss(src_serialized_row);
boost::archive::text_iarchive ia(ss);
table_row * dest = this;
ia >> dest; // this is fine, compiles.
return dest;
}
table_row* table_row::deserialize_row(std::string src_serialized_row) {
std::stringstream ss(src_serialized_row);
boost::archive::text_iarchive ia(ss);
ia >> this; //error, >> operator does not match [error]
return this;
}

[错误] 我真的不明白这一点。我在两个代码示例中传递相同的指针,对吗?为什么会是一个错误?

唯一的区别是this是一个 prvalue,将其分配给dest将使其成为左值。

我假设运算符看起来像这样:

template<class T>
boost::archive::text_iarchive& operator>>(
boost::archive::text_iarchive& ia,
T& archive_to
);

this这样的右值无法绑定到非 const 左值引用,因为它试图将指针设置为反序列化值(可能不是您想要的(。