【问题标题】:Casting from string to void* and back从字符串转换为 void* 并返回
【发布时间】:2011-01-26 12:14:11
【问题描述】:

是否可以从 void* 重新映射 STL 类对象?

#include <string>

void func(void *d)
{
    std::string &s = reinterpret_cast<std::string&>(d);
}

int main()
{
    std::string s = "Hi";
    func(reinterpret_cast<void*>(&s));
}

【问题讨论】:

  • 为什么要这样做?你有什么可能的理由想要reinterpret_castvoid*? (对于它的价值,转换 void* 是隐式的,不需要强制转换。当转换回来时,static_cast 就足够了。)
  • @Nick:许多不正确的代码似乎“有效”。您应该测试代码是否存在编译器和其他错误,但没有错误并不意味着没有问题。
  • @James:在实际代码中,string s 是临时的,一旦通过 func 就会被销毁。我正在寻找绑定对由 void* 传递的临时变量的引用。
  • 您至少误解了两件事:1)调用函数时创建的临时对象在函数返回之前不会被销毁;2)您只能通过将临时对象绑定到在创建时立即引用,而不是通过传递它然后绑定它。

标签: c++ casting


【解决方案1】:

使用 static_cast 将 void 指针转换回其他指针,只需确保转换回与最初使用的完全相同的类型。转换为 void 指针不需要强制转换。

这适用于任何指针类型,包括来自 stdlib 的类型的指针。 (技术上任何指向对象类型的指针,但这就是“指针”的含义;其他类型的指针,例如指向数据成员的指针,需要限定。)

void func(void *d) {
  std::string &s = *static_cast<std::string*>(d);
  // It is more common to make s a pointer too, but I kept the reference
  // that you have.
}

int main() {
  std::string s = "Hi";
  func(&s);
  return 0;
}

【讨论】:

    【解决方案2】:

    我改写如下,

    #include<string>
    
    void func(void *d)
    {
        std::string *x = static_cast<std::string*>(d);
    /* since, d is pointer to address, it should be casted back to pointer
       Note: no reinterpretation is required when casting from void* */
    }
    
    int main()
    {
        std::string s = "Hi";
        func(&s); //implicit converssion, no cast required
    }
    

    【讨论】:

      【解决方案3】:

      您的代码不应该编译。 改变

      std::string &s = reinterpret_cast<std::string&>(d);
      

      std::string *s = static_cast<std::string*>(d);
      

      编辑: 更新了代码。使用static_cast 而不是reinterpret_cast

      【讨论】:

      • 不需要诊断,它可以在许多编译器上编译; reinterpret_cast 很大程度上是由实现定义的。
      • 是的,你是对的。 static_cast 就足够了,因为我们处理 void *
      【解决方案4】:

      是的,这是可能的,但是您尝试从指向void * 的指针进行转换,然后再转换为引用reinterpret_cast 运算符只允许转换回与您开始时完全相同的类型。试试这个:

      void func(void *d)
      {
          std::string &s = *reinterpret_cast<std::string*>(d);
      }
      

      【讨论】:

      • static_cast 也可以在这里工作。我认为,您的代码比 OP 的代码更好,因为它不需要 reinterpret_cast,所以您最好利用这一点!
      猜你喜欢
      • 2018-12-24
      • 1970-01-01
      • 2016-02-05
      • 1970-01-01
      • 2011-02-02
      • 1970-01-01
      • 1970-01-01
      • 2018-01-21
      • 2014-06-11
      相关资源
      最近更新 更多