为什么我不能像这样在 QMap 上调用 insert ?
尝试在 Qt SDK 4.7.4 for Desktop - MinGW 4.4 下编译以下代码会导致以下编译器错误:
#include <QtCore/QCoreApplication>
#include <QMap>
struct Buffer
{
char data[4];
};
// A Bucket needs to reserve 16 chars worth of Buffers
typedef Buffer Bucket[(16 * (sizeof (char))) / (sizeof (Buffer))];
typedef QMap<QString, Bucket *> BucketMap;
int main(int argc, char *argv[])
{
BucketMap bucket;
bucket.insert(QString("foo"), new Bucket()); //compile error
return 0;
}
../test/main.cpp: In function 'int main(int, char**)':
../test/main.cpp:13: error: no matching function for call to 'QMap<QString, Buffer (*)[4]>::insert(QString, Buffer*)'
../../../QtSDK/Desktop/Qt/4.7.4/mingw/include/QtCore/qmap.h:556: note: candidates are: QMap<Key, T>::iterator QMap<Key, T>::insert(const Key&, const T&) [with Key = QString, T = Buffer (*)[4]]
mingw32-make.exe[1]: *** [debug/main.o] Error 1
mingw32-make.exe: *** [debug] Error 2
我尝试使用 std::string
和 std 将其转换为等效示例::map
达到相同的效果。我提供了 Qt 版本,因为它更紧凑,并且最终是我的项目所需的形式。
我猜我只是错过了有关 typedef 最终如何解释的一些内容。为什么 insert
显然是一个 Buffer *
(不是 Buffer(*)[4]
),我该如何修复它?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
简单回答:类型不匹配。
您实际上需要了解的是:您不能为数组类型调用 new 表达式。因此,以下两个是不等价的(并且第一个是不合法的):
该语言不能那样工作。第二个版本创建一个动态数组,而第一个版本想要创建“4 T 数组”类型的单个动态对象,这是不可能的。相反,
new TArr
实际上与new T[4]
相同,因此结果是一个由四个T 组成的动态数组
s.*您基本上应该将地图的值类型更改为
Buffer *
或std::array; *
或std::unique_ptr
或std::unique_ptr>
,无论您选择哪个更喜欢。*) 这正是以下代码非常有问题的原因:
template; void foo() { T * p = 新 T;删除p; }
想象你说foo();
...Simple answer: The types don't match.
What you actually need to know: You cannot invoke a
new
expression for an array type. Therefore, the following two are not equivalent (and the first isn't legal):The language just doesn't work that way. The second version creates a dynamic array, while the first version would like to create a single dynamic object of type "array of 4 T", which is not possible. Instead,
new TArr
is actually the same asnew T[4]
, and so the result is a dynamic array of fourT
s.*You should basically just change your map's value type to either
Buffer *
orstd::array<Buffer, 4> *
orstd::unique_ptr<Buffer[]>
orstd::unique_ptr<std::array<Buffer, 4>>
, whichever you prefer.*) This is exactly the reason why the following code is very problematic:
template <T> void foo() { T * p = new T; delete p; }
Imagine you sayfoo<int[4]>();
...您的问题出在
typedef
中。尝试以下操作:您将看到
bs
的值为 4 (INT_PTR
);Your problem is in the
typedef
. Try the following:and you will see that the value of
bs
is 4 (INT_PTR
);