如何插入“const Obj”进入 std::list?
我写了一个函数
void addAnything(T const &obj)
{
...
m_list.push_front(obj); // - line returns C2664 - list is initialized by std::list<T*> m_list
...
}
,我的问题是从“T *const”中的“const T”转换。我需要将它插入到这个列表中... =/ 任何将元素插入 std::list 的方法都需要 'const T& x'。 有没有办法将 const 项插入到我的列表中并保留 addAnything() 的参数? 也许通过调整 m_list ?
感谢您的任何建议!
I wrote a function
void addAnything(T const &obj)
{
...
m_list.push_front(obj); // - 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!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
您有一个 const 对象,并且尝试将其插入到指向非 const 对象的非 const 指针的容器中。我假设您打算使用
&obj
,但即使如此,这也行不通:如果obj
是临时的怎么办?您需要将obj
制作为T&
,或者制作obj
的副本(可能使用new
)并推送该地址。请注意,当您有一个< /代码>。
T*
容器时,并不总是清楚谁拥有其中的T
。除非您明确不希望容器取得所有权(在这种情况下,推送新内容是一个坏主意),否则您可能需要使用 boost::ptr_listYou 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 ifobj
is a temporary? You'll need to either makeobj
aT&
, or make a copy ofobj
(probably withnew
) and push the address of that.Note that when you have a container of
T*
, it is not always clear who owns theT
s in it. Unless you explicitly don't want the container to take ownership (in that case, pushingnew
ed things is a bad idea), you may want to useboost::ptr_list<T>
.试试这个:
Try this:
您的代码有两个问题:首先,当列表需要指针时,您正在推送对象引用;其次,您的列表需要一个非常量指针。您可以通过创建 obj 的副本或将列表的类型更改为 std::list来解决第二个问题。
请注意,使用第二种方法时,您必须确保
obj
在您将指向它的指针存储在m_list
中时有效。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 tostd::list<const T*>
.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 inm_list
.您知道 std::list吗?定义?当对象从列表中删除时,您应该手动删除该对象。与 std::list。
我不会替换 std::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
的类型为std::list
。这意味着,m_list
可以保存T*
类型的元素。但是您正在推送类型为T&
的obj
。引用不是指针。Error message complains you that the
m_list
is of typestd::list<T*>
. Meaning,m_list
can hold elements of typeT*
. But you are pushingobj
which is of typeT&
. References are not pointers.