gpt4 book ai didi

c++ - C++ 中的引用和指针类型转换

转载 作者:太空宇宙 更新时间:2023-11-04 12:44:15 25 4
gpt4 key购买 nike

我可以对 vector<void*> 的引用进行类型转换引用vector<Foo*>而我无法输入 vector<void*> to vector<Foo*> .我收到错误 C2440:“reinterpret_cast”:无法从“std::vector<_Ty>”转换为“std::vector<_Ty>”,为什么?

而且我能够将 void* 类型转换为 Foo* 而不会出现编译器错误。

void* g =&foo;
reportFooVector2(reinterpret_cast<Foo*>(g));

下面是我的全部代码。

#include "stdafx.h"
#include <iostream>
#include <vector>
using namespace std;

struct Foo
{
string s;
int i;
};


void reportFooVector( vector <Foo*> * pvf )
{

}


void reportFooVector1( vector <Foo*> pvf )
{
}

void reportFooVector2( Foo *pvf )
{
}


int main()
{
struct Foo foo = {"foo", 5};
struct Foo goo = {"goo", 10};
void* g =&foo;
reportFooVector2(reinterpret_cast<Foo*>(g));
vector <void *> vf;
vf.push_back(&foo);
vf.push_back(&goo);
reportFooVector1( reinterpret_cast< vector < Foo * > >(vf));
reportFooVector( reinterpret_cast< vector < Foo * > * >(&vf));
}

在上面的程序中,我得到编译器error C2440: 'reinterpret_cast' : cannot convert from 'std::vector<_Ty>' to 'std::vector<_Ty>' when calling这条线 reportFooVector1( reinterpret_cast< vector < Foo * > >(vf));

能请大家说说原因吗?

最佳答案

首先在高层次上是什么 reinterpret_cast 做什么?

  • Converts any pointer type to any other pointer type, even of unrelated classes
  • Cast pointers to or from integer types

请注意,这里所做的一切都涉及指针类型之间的转换、到指针类型或从指针类型的转换。所以重要的是要注意 reinterpret_cast<vector<Foo*>>(vf)无效,因为它转换了 vector<void*>vector<Foo*> .尽管这些都是 vector 包含指针,vf也不vector<Foo*>本身就是一个指针。

解决了这个让我们讨论 reinterpret_cast<vector<Foo*>*>(&vf)如果由于 Type Aliasing 上的规则而取消引用,这也是将导致未定义的行为.
鉴于 reinterpret_cast 的输入是 DynamicType 并且输出是 AliasedType reinterpret_cast仅在以下情况下有效:

  • AliasedType and DynamicType are similar
  • AliasedType is the (possibly cv-qualified) signed or unsigned variant of DynamicType
  • AliasedType is std::byte, char, or unsigned char: this permits examination of the object representation of any object as an array of bytes

Informally, two types are similar if, ignoring top-level cv-qualification:

  • They are the same type
  • They are both pointers, and the pointed-to types are similar
  • They are both pointers to member of the same class, and the types of the pointed-to members are similar
  • They are both arrays of the same size or both arrays of unknown bound, and the array element types are similar

因为关于 vector<void*>* 这些都不是真的和 vector<Foo*>*取消引用此 reinterpret_cast 的输出是未定义的行为。


既然我们已经讨论了为什么这两者都不受欢迎;让我建议你改为:void reportFooVector(void** pvf, const size_t count)您可以通过以下方式调用它:reportFooVector(data(vf), size(vf))内部发送至 reportFooVector您需要将单个元素转换为 Foo* s 以便对它们进行操作。

关于c++ - C++ 中的引用和指针类型转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52497993/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com