Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
165 views
in Technique[技术] by (71.8m points)

c++ - Vector of const objects giving compile error

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

But if declare -

vector <A> mylist;

my code compiles.

Is const not allowed in this context?

I am copying my code here for everyone'e reference -

#include <iostream>
#include <vector>

using namespace std;
class A
{
public:
    A () {cout << "default constructor
";}
    A (int i): m(i) {cout << "non-default constructor
";}

private:
    int m;
};

int main (void)
{
    vector<const A> mylist;

    mylist.push_back(1);

    return 0;
}
question from:https://stackoverflow.com/questions/17313062/vector-of-const-objects-giving-compile-error

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Items in a vector must be assignable (or, in more recent versions of the standard, movable). 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).

I suppose for the truly pedantic, 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;
    }
};

I believe you 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++. This failed with some older compilers (e.g., failed with g++ 4.8.1), but works with reasonably recent ones (VC++ back to at least 2015, g++ back to at least 5.4 and clang++ back to at least 4.0--though I haven't tried to track down the first version of each that supported it).

For a current compiler, a type that supported moving const objects would probably work just as well. But, just in case it wasn't obvious: this is allowing you to modify an object even though it's marked const. That's clearly a direct violation of any reasonable user's expectations, so it's mostly a problem, not a solution.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...