在C++中,st*:: move在T*类型上的意外行为

Ana*_*rni 4 c++ typeid decltype c++11 value-categories

我有下面的代码段,其中i声明一个称为变量pval,其尝试导出T&&上的T*[与Tint].根据类型信息[使用abi解码],导出的类型是int*.

但是当我比较它的int*类型时,decltype(pval)它返回零而不是1,这意味着它被视为pval不同的类型int*.那么哪一个是由报告的错误pval存在或哪个指示比较为错误.int*typeidis_same

#include<iostream>
#include<string>
#include<typeinfo>
#include<cxxabi.h>
#include<type_traits>

using namespace std;

std::string classname(const std::type_info& info)
{
    int status;
    char* rslt=abi::__cxa_demangle(info.name(),0,0,&status);
    std::string result(rslt);
    free(rslt);
    return result;
}

int main(int argc, char* argv[])
{
    int* ptr = new int(10);
    decltype(std::move(ptr)) pval = std::move(ptr);
    cout << classname(typeid(pval)) << endl;             // as per typeid information the type of pval is int*.

    bool isSame = is_same<decltype(pval), int*>::value;  // What then is the pval not same as int* as per is_same ? 
    cout << "isSame status = " << isSame << endl;
    cout << is_same<int*, int*>::value << endl;
    return(0);
}
Run Code Online (Sandbox Code Playgroud)

son*_*yao 6

行为decltypetypeid不同.

确切的类型pvalint* &&,即rvalue-reference to int*.(这就是为什么在将它与类型进行比较时std::is_same返回的原因.)根据行为,falseint*decltype

如果表达式的值类别是xvalue,则decltype产生T &&;

std::move(ptr)返回的是xvalue.

以下表达式是xvalue表达式:

  • 函数调用或重载的运算符表达式,其返回类型是对象的右值引用,例如std::move(x);

然后给出decltype(std::move(ptr)) pval,类型pval将是int* &&.

另一方面,行为typeid是不同的.

std::type_info代表示类型的对象type.如果type是引用类型,则结果引用std::type_info表示引用类型的对象.

这意味着std::type_info返回的对象typeid(pval)将引用引用的类型,即int*不引用int* &&.


BTW:std::type_info::name返回的是实现定义.