使用push_back时的语义问题
std::vector Semantic issue while using push_back
#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::vector
和const
这样的元素。
解决方案:
使指针非- 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中工作得很好)
相关文章:
- 警告处理为错误这里有什么问题
- Xcode 语义问题引用或以前定义的代码
- Xcode(版本9.2(9C40B)):试图包括Boost时C 语义和链接器问题
- 由于libkern.h中的语义问题,Xcode Build失败
- 解析问题:预期的不合格的ID和语义问题:C 需要所有声明的类型说明符
- 二进制表达式的语义问题无效操作数("双精度"和"双精度")
- 将 Xcode 项目与 MathGL 链接时的语义问题
- 语义问题:调用'displayBoard'没有匹配函数
- xcode 构建错误:从指针到较小类型"int"的语义问题丢失了信息
- 语义问题 "Attempt to use a deleted function" 遇到使用 std::线程用法编译 c++ 代码
- 成功包含文件,现在处理语义问题
- 重载迭代器:c++语义问题
- 关于对象初始化语义的问题
- C++语法/语义问题:对Function和typedef关键字的引用
- C++Friend语法/语义问题
- 关于声明语义的几个问题
- C++ 语义问题:"'use of undeclared identifier 'balance'"
- Mersenne Twister & 接收算法中的语义问题.h
- C++11 移动语义行为特定问题
- 使用push_back时的语义问题