MSVCC/g++/icc 中 std deque/向量之间的不同行为
我有这段非常简单的代码;
#include <deque>
#include <vector>
using namespace std;
class A
{
public:
A(){};
~A(){};
deque<A> my_array; // vector<A> my_array;
};
int main(void)
{
}
如果我在 Linux 上使用 g++ 和 icc/icpc 编译此代码,它编译得很好,即使使用 -Wall
它也不会发出警告。如果我将双端队列交换为向量,情况是一样的。
我想使用 MSVCC (cl) 在 Windows 上构建此代码,但不幸的是它会抛出错误 c2027:
error C2027: use of undefined type 'A'
但是如果我将 std::deque
更改为 std::vector
它可以在 Visual Studio 2010 中正常编译。
我的问题是;由于某种原因这种行为是可以预料的吗?如果是这样,为什么编译器之间存在差异,或者这是 g++/icc 或 MSVCC 的错误?
I have this very simple piece of code;
#include <deque>
#include <vector>
using namespace std;
class A
{
public:
A(){};
~A(){};
deque<A> my_array; // vector<A> my_array;
};
int main(void)
{
}
If I compile this code with both g++ and icc/icpc on linux it compiles fine, even with -Wall
it gives no warnings. If I swap the deque to a vector the situation is the same.
I would like to build this code on windows using MSVCC (cl) but unfortunately it throws error c2027:
error C2027: use of undefined type 'A'
If however I change the std::deque
to a std::vector
it compiles fine with Visual Studio 2010.
My question is; is this behaviour to be expected for some reason? If so, why are there differences between compilers or is this a mistake with either g++/icc or MSVCC?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这是未定义的行为(对于
std::deque
和std::vector
都是如此,所以无论一个实现用它做什么都可以,只要
标准有关。您正在实例化一个标准容器
不完整的类型。
使用 g++ 编译时,
-Wall
(一般来说,所有选项都以与
-W
)仅涉及语言。对于图书馆问题,您应该使用
-D_GLIBCXX_CONCEPT_CHECKS -D_GLIBCXX_DEBUG 进行编译
也是如此。 (如果这导致性能-D_GLIBCXX_DEBUG_PEDATIC
问题,您可以删除优化构建中的最后两个
-D
。)It's undefined behavior (both with
std::deque
and withstd::vector
,so whatever an implementation does with it is fine, as far as the
standard is concerned. You're instantiating a standard container with
an incomplete type.
When compiling with g++,
-Wall
(and in general, all options startingwith
-W
) only concern the language. For library issues, you should becompiling with
-D_GLIBCXX_CONCEPT_CHECKS -D_GLIBCXX_DEBUG
as well. (If this causes performance-D_GLIBCXX_DEBUG_PEDANTIC
problems, you can remove the last two
-D
in optimized builds.)除了 James Kanze 的回答之外,我四处搜索并发现这篇 Dobbs 博士文章,它解释了该标准对使用不完整类型的容器的立场。
此外,它还暗示了它适用于
vector
但不适用于deque
的原因,即实现。典型的向量可能类似于不完整类型,因为我们只有一个指向
T
的指针,但deque
可以很好地以这样的方式实现(在 VS2010 中):它按值使用T
,从而使其与不完整类型不兼容。Further to James Kanze's answer I searched around and found this Dr Dobbs article which explains the standard's stance on using containers with incomplete types.
Further it hints at that the reason it works with
vector
s but notdeque
s, namely the implementation. A typical vector may be something likewhich is okay with imcomplete types since we have only a pointer to
T
butdeque
could well be implemented in such a way (in VS2010) that it makes use ofT
by value thus rendering it incompatible with incomplete types.