我试图找出为什么以下代码片段调用 LValue 强制转换运算符重载:
#include <iostream>
class Foo
{
public:
Foo(int i = 0) : i(i) {}
operator const int& () const &
{
std::cout << "lvalue\n";
return i;
}
operator int () const &&
{
std::cout << "rvalue\n";
return i;
}
int i = 0;
};
Foo Fool()
{
return Foo(5);
}
int main()
{
const int& i = Fool();
const int j = Fool();
return 0;
}
Run Code Online (Sandbox Code Playgroud)
目前的输出是:
左值
右值
但根据我的理解,Fool()返回一个rvalue并且由于const&可以绑定到rvalues所以不需要构造一个 …
嗨考虑下面的用例:
int main() {
std::shared_ptr<int> shared_ptr_to_int;
std::cout << typeid(int).name() << std::endl;
std::cout << typeid(decltype(*shared_ptr_to_int)).name() << std::endl;
if (std::is_same<decltype(*shared_ptr_to_int), int>::value) {
std::cout << "is same!\n";
}
else {
std::cout << "not the same!\n";
}
system("pause");
}
Run Code Online (Sandbox Code Playgroud)
对于我的测试用例,我得到的结果"不一样"
我不确定为什么它不会导致价值成真.有人可以向我解释发生了什么事吗?
PS:我的最终目标是将shared_ptr中存储的类型与另一种类型进行比较(在此测试用例中,此类型为int)
感谢您的关注!