问题描述
我已在我的代码中声明了以下内容
I have declared the following in my code
vector <const A> mylist;
我得到以下编译错误 -
I get the following compile error -
new_allocator.h:75: error: `const _Tp* __gnu_cxx::new_allocator<_Tp>::address(const _Tp&) const \[with _Tp = const A]' and `_Tp* __gnu_cxx::new_allocator<_Tp>::address(_Tp&) const [with _Tp = const A]' cannot be overloaded
但如果声明 -
vector <A> mylist;
我的代码编译。
不允许在此上下文中?
我复制我的代码在这里供大家参考 -
I am copying my code here for everyone'e reference -
#include <iostream>
#include <vector>
using namespace std;
class A
{
public:
A () {cout << "default constructor\n";}
A (int i): m(i) {cout << "non-default constructor\n";}
private:
int m;
};
int main (void)
{
vector<const A> mylist;
mylist.push_back(1);
return 0;
}
推荐答案
可分配。 const
对象不可分配,因此尝试将它们存储在向量中将失败(或至少可失败 - 代码无效,但是编译器可以自由地接受它,如果它这样选择,虽然大多数程序员通常喜欢无效的代码被拒绝)。
Items in a vector must be assignable. const
objects aren't assignable, so attempting to store them in a vector will fail (or at least can fail -- the code is invalid, but a compiler is free to accept it anyway, if it so chooses, though most programmers would generally prefer that invalid code be rejected).
编辑:我想真正拙劣,我应该添加一个纯理论的可能性。如果你想要足够糟糕,你可以定义一个可分配类型,尽管 const
,类似这样:
I suppose for the truly pedantic, I should probably add a purely theoretical possibility. If you wanted to badly enough, you could define a type that was assignable despite being const
, something like this:
class ugly {
mutable int x;
public:
ugly const &operator=(ugly const &u) const {
x = u.x;
return *this;
}
};
至少在理论上,我相信你可能即使它们 const
,这种类型的项目也会在向量
中。用VC ++创建这些成功向量的快速测试,但失败与gcc(g ++ 4.8.1 / MinGW)。从技术上来说,我认为这可能是g ++(或其库)中的一个错误,但我不能说它是一个我认为是主要问题。恰恰相反,我不知道(有一点)它是否可能不是实际的故意,试图保存程序员做一些可怕和愚蠢的事情。
At least in theory, I believe you probably should be able to store items of this type in a vector
even though they're const
. A quick test of creating a vector of these succeeds with VC++, but fails with gcc (g++ 4.8.1/MinGW). Technically, I think this probably qualifies as a bug in g++ (or its library), but I can't say it's one I see as as major problem. Rather the contrary, I wonder (a little) whether it may not actually be intentional, in an attempt at saving the programmer from doing something horrible and stupid.
这篇关于向量的const对象给出编译错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!