开发者

How to insert 'const Obj' into std::list<T*>?

I wrote a function

    void addAnything(T const &obj)
    {
    ...
    m_list.push_front(obj); // -开发者_JAVA技巧 line returns C2664 - list is initialized by std::list<T*> m_list
     ...
    }

and my Problem is to convert from 'const T' in 'T *const'. And I need to insert it into this list... =/ Any method for inserting elements into a std::list requires 'const T& x'. Is there any way to insert an const item into my list and keep the parameter of addAnything()? Maybe by adapting m_list?

Thx for any advice!


You have a const object, and you're trying to insert it into a container of non-const pointers to non-const objects. I'm going to assume you meant to use &obj, but even then, this isn't going to work: what if obj is a temporary? You'll need to either make obj a T&, or make a copy of obj (probably with new) and push the address of that.

Note that when you have a container of T*, it is not always clear who owns the Ts in it. Unless you explicitly don't want the container to take ownership (in that case, pushing newed things is a bad idea), you may want to use boost::ptr_list<T>.


Try this:

m_list.push_front(new T(obj));


There are two problems with your code: first, you are pushing an object reference when the list expects a pointer; second, your list requires a non-const pointer. You can solve the second problem by either creating a copy of obj or changing the list's type to std::list<const T*>.

// 1.
m_list.push_front(new T(obj)); // don't forget to delete it later

// 2.
std::list<const T*> m_list;
m_list.push_front(&obj);

Note, that with the second method, you have to make sure that obj is valid for as long as you store a pointer to it in m_list.


Are you aware of std::list<T*> definition? Manually you should delete object when is removed from the list. I not than replace std::list<T*> with std::list<T>.


 m_list.push_front(obj); 
// - line returns C2664 - list is initialized by std::list<T*> m_list

Error message complains you that the m_list is of type std::list<T*>. Meaning, m_list can hold elements of type T*. But you are pushing obj which is of type T&. References are not pointers.

Is there any way to insert an const item into my list and keep the parameter of addAnything()? Maybe by adapting m_list?

std::list<const T> m_list;
void addAnything( const T& obj ){
     m_list.push_front(obj);

     // ...

}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜