2

I am building an STL list. I made a decorator class (MyList) that is a list of a special class (ProtectMe). I want all of the items of the list to be const. So here's what I made:

#include <list> using namespace std; class ProtectMe{ private: int data_; public: ProtectMe(int data):data_(data){ } int data() const{return data_;} }; class MyList{ private: //A list of constant pointers to constant ProtectMes. list<const ProtectMe* const> guts_; public: void add(const ProtectMe& data){ guts_.push_front(&data); } }; 

I get the following compile error:

 error: ‘const _Tp* __gnu_cxx::new_allocator::address(const _Tp&) const [with _Tp = const ProtectMe* const]’ cannot be overloaded 

I'm still scratching my head trying to decode where I went wrong. Why doesn't this code compile? What should I change?

3
  • 2
    guts_.push_front(const &data); Why keyword const in brackets ? Why do you wish list elements to be of pointers type ? Commented Jul 6, 2012 at 20:04
  • @Mahesh: No good reason. Just trying to make it compile. It obviously didn't help. I'll remove it... Commented Jul 6, 2012 at 20:06
  • Why not just list<ProtectMe> are you deriving from ProtectMe somewhere else??? Commented Jul 6, 2012 at 20:12

1 Answer 1

2

The value_type of standard containers must be CopyInsertable (or MoveInsertable) in order for the push_front to work. The value type of list<const ProtectMe* const> is constant, so it's not CopyInsertable.

CopyInsertable means that

allocator_traits<A>::construct(m, p, v); 

is well defined where p is a pointer to value_type, which by default calls placement new on p and thus requires it to be a non-const pointer.

Sign up to request clarification or add additional context in comments.

2 Comments

Interesting..So, how would I have a list of const objects? As the name implies, I want ProtectMe to be read-only. Imagine there is a non-const method in ProtectMe...
@User1: list<const ProtectMe*> is enough, you won't be able to modify the pointed ProtectMes.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.