使用push_back时的语义问题

std::vector Semantic issue while using push_back

本文关键字:语义 问题 back push 使用      更新时间:2023-10-16
#include <vector>
typedef void (* const MyType)(void *, void *);
static void exampleFunction(void *param1, void *param2)
{
    // ...
}
int main(int argc, char* argv[])
{
    std::vector<MyType> myVector;
    myVector.push_back(exampleFunction); // fails.
} 

这是代码,看起来//fails的行是不可编译的。我把它注释掉,没有问题。但如果它是打开的,这是XCode中的错误:

/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/c++/v1/memory:1593:27: Cannot initialize a parameter of type 'void *' with an lvalue of type 'void (*const *)(void *, void *)'

有人知道为什么会发生这种情况吗?

Vector(以及任何其他标准容器)以特定的方式管理其元素的内存。允许执行的许多操作都要求元素不能是const。例如,它的fill_n方法用相同值的副本填充一个范围。或使用位置new:

构造元素
 /**
 * Constructs an object in existing memory by invoking an allocated
 * object's constructor with an initializer.
 */
 template<typename _T1, typename _T2>
  inline void
  _Construct(_T1* __p, const _T2& __value)
  {
    // _GLIBCXX_RESOLVE_LIB_DEFECTS
    // 402. wrong new expression in [some_]allocator::construct
    ::new(static_cast<void*>(__p)) _T1(__value);
                     ^
                    // here you would get an error: invalid static_cast
  }

没有std::vectorconst这样的元素。


解决方案:

使指针非- const:

typedef void (* MyType)(void *, void *);

为了在许多不同的编译器中获得最大的兼容性,请做以下更改:

typedef void (*MyType)(void *, void *);

^删除const

void exampleFunction(void *param1, void *param2)

^删除静态

myVector.push_back(&exampleFunction);

^添加&

您必须将typedef更改为:

typedef void (* MyType)(void *, void *);

(作为旁注,它在VS2013中工作得很好)