2013-08-27 47 views
1

我使用QueryInterface函数,该函数将根据IID返回给定接口上的指针。GCC警告“解引用类型指针会破坏严格别名规则”

DecodingFramework::IVariableFramerate* pInt = NULL; 
DecodingFramework::DecodeResult iVFR = pVideoDescription->QueryInterface(IID_IVariableFramerate, (void**)(&pInt)); 
if(pInt != NULL && iVFR == DF_SUCCESS) 
{ 
    //use the IVariableFramerate interface using pInt 
} 

但在该代码(void**)(&pInt)产生与消息的错误dereferencing type-punned pointer will break strict-aliasing rules

我的代码更新到以下几点:

void* pInt = NULL; 
DecodingFramework::DecodeResult iVFR = pVideoDescription->QueryInterface(IID_IVariableFramerate, &pInt); 
if(pInt != NULL && iVFR == DF_SUCCESS) 
{ 
    DecodingFramework::IVariableFramerate* pVideoVFR = reinterpret_cast<DecodingFramework::IVariableFramerate*>(pInt); 

    //use the IVariableFramerate interface using pVideoVFR 
} 

我发现很多相关的警告信息,但问题主要是当投射更复杂的数据,而不仅仅是地址指针到void**? 真的有问题吗?我不明白这个警告背后的理由。

+2

可能有帮助,关于严格别名的好文章[Type-punning and strict-aliasing](http://blog.qt.digia.com/blog/2011/06/10/type-punning-and-strict ),这是一个更详细的内容,但要消化[理解严格别名](http://cellperformance.beyond3d.com/articles/2006/06/understanding-strict-aliasing.html)需要更长的时间。 –

+2

您是否阅读过其他许多问题(和答案),标题中的警告信息完全相同? –

+0

当'QueryInterface'为'pInt'赋值时,它使用的左值是什么类型?如果该左值与DecodingFramework :: IVariableFramerate *不兼容,则更新后的代码仍然违反别名规则。 –

回答

4

这也是为什么说谎有关指针类型的编译器是坏:

struct SomeClass { int a; }; 
SomeClass* global_pointer; 

void open_object(void** result, int x) 
{ 
    cout << global_pointer->a; 
    *result = new SomeClass{x}; 
    cout << global_pointer->a; 
} 

编译器是完全允许更换由:

auto temp = global_pointer->a; 
cout << temp; 
*result = new SomeClass{x}; // according to the Standard, the compiler is allowed to assume this line CANNOT change global_pointer, because the type is wrong 
cout << temp; 

如果你再调用

open_object((void**)&global_pointer); 

那么你可能会对结果感到惊讶。

相关问题