【问题标题】:Conversion from 'void *' to 'vector<int *>'从 'void *' 到 'vector<int *>' 的转换
【发布时间】:2021-07-28 01:26:14
【问题描述】:

我将向量指针转换为指向函数的 void 指针。在该函数中,如何将其转换为向量指针?

in main

vector<int *> foo;
function(&foo);

in function
function(void *bar){
    auto temp = bar; // what replaces auto or what should bar be cast to?
    temp.pushback(something);
}

我希望我没有弄错术语,任何意见都有帮助!

【问题讨论】:

  • 投回去有什么问题?
  • 在函数内部, bar 被视为 'void *' 但我想将其用作 'vector'
  • @mediocrevegetable1 static_cast 可以正常工作
  • 我猜房间里的大象是你的设计以void*开头的原因。鉴于 C++ 类型安全,使用void * 的原因是什么?
  • 当您标记c++11 时,您可能应该切换到std::thread

标签: c++ c++11 pointers vector casting


【解决方案1】:

您没有强制转换它,但这只是一种隐式转换。该方法称为push_back,您需要-&gt; 才能取消引用。

如果您绝对确定 void* 指向 vector&lt;int*&gt;,则可以安全地将其转换回:

#include <vector>

void function(void *bar){
    auto temp = static_cast<std::vector<int*>*>(bar);
    temp->push_back(new int);
}

int main() {
    std::vector<int *> foo;
    function(&foo);
}

然而,问题出现了:为什么所有的指针?如果您可以通过任何方式更改 function 并且该向量应该存储整数,您的代码应该如下所示:

#include <vector>

void function(std::vector<int>& v){
    v.push_back(42);
}

int main() {
    std::vector<int> foo;
    function(foo);
}

【讨论】:

    【解决方案2】:

    您可以申请static_cast

    这是一个演示程序。

    #include <iostream>
    #include <vector>
    
    void function( void *bar )
    {
        auto pv = static_cast<std::vector<int *> *>( bar );
        
        for ( const auto &p : *pv ) std::cout << *p << ' ';
        std::cout << '\n';
    }
    
    int main() 
    {
        int a[] = { 1, 2, 3 };
        std::vector<int *> v;
        
        for ( auto &x : a ) v.push_back( &x );
        
        function( &v );
        
        return 0;
    }
    

    程序输出是

    1 2 3
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-08-29
      • 1970-01-01
      • 1970-01-01
      • 2016-06-06
      • 2018-08-23
      • 2016-11-11
      相关资源
      最近更新 更多