【问题标题】:Why is converting from int to char* different from converting from std::string to char*?为什么从 int 转换为 char* 与从 std::string 转换为 char* 不同?
【发布时间】:2015-07-24 15:09:16
【问题描述】:

我正在学习 C++ 并阅读 Andrei Alexandrescu 关于泛型编程的书。他提出了一个模板类,可以用来在类型之间进行转换:

template <class To, class From>
To safe_reinterpret_cast(From from)
{
    assert(sizeof(From) <= sizeof(To));
    return reinterpret_cast<To>(from);
}

这适用于:

int i = 5;
char* p = safe_reinterpret_cast<char*>(i);

但失败了

std::string a("apple");
char* pp = safe_reinterpret_cast<char*>(a);

这是编译时的错误失败:

invalid cast from type 'std::basic_string<char>' to type 'char*'

为什么这个演员会失败?

【问题讨论】:

    标签: c++ reinterpret-cast


    【解决方案1】:

    Andrei Alexandrescu 臭名昭著的示例仅适用于普通旧数据类型。

    适用于指针。转换不相关的指针类型的行为是未定义的。

    您可以void* 重新解释转换为 void*,并将 void* 重新解释转换回原始指针类型。

    【讨论】:

    • 我认为这里的重点是std::string 不是指针,也不是 POD。
    【解决方案2】:

    因为intchar 是原始类型,而std::string 不是。

    【讨论】:

    • 所以我更大的问题是 reinterpret_cast 永远不能用于非原始类型?
    猜你喜欢
    • 2011-07-23
    • 2020-04-05
    • 2023-01-06
    • 2014-07-23
    • 1970-01-01
    • 2014-05-04
    • 1970-01-01
    • 2012-12-11
    相关资源
    最近更新 更多