简体   繁体   English

C ++中的STL列表指针

[英]STL List pointers in C++

How can I access a list in C++ by de-referencing the List pointer? 如何通过取消引用列表指针来访问C ++中的列表?

I get bad_alloc error when doing: 我在执行时收到bad_alloc错误:

 List My_List = *ls;

ls is a List* . ls是一个List* before in code, I had: 在编写代码之前,我有:

List* ls = & Temp_List;

I used the value of ls as an integer. 我将ls的值用作整数。 I passed it through different functions. 我通过不同的功能。 Now that I want to cast it back to List* and de-reference it, I get the error 现在,我想将其投射回List*并取消引用,我得到了错误

If you allocate the list on stack, its address might get changed. 如果在堆栈上分配列表,则其地址可能会更改。 But if you allocate it on heap, you won't lose the pointer to the list (new or malloc) 但是,如果在堆上分配它,则不会丢失指向列表的指针(新的或malloc的)

试试看,

List *My_List = ls;

Actually, you did dereferenced your list pointer in this piece of code: *ls; 实际上,您确实在这段代码中取消了对列表指针的引用: *ls;

And then you created new list object on the stack in this code: List My_List and copied your list into this list in this piece of code: <newly created list> = <your list reference> 然后,您使用以下代码在堆栈上创建了新的列表对象: List My_List并将您的列表通过以下代码List My_List 复制到该列表中: <newly created list> = <your list reference>

(heh. after applying dereference operator you get the reference. That's c++ for you) (呵呵。在应用取消引用运算符后,您将获得引用。这是适合您的c ++)

and during this copy you probably get std::bad_alloc because copying lists involves memory allocations, and probably your original list is destroyed and hence your pointer to original list points at some random garbage, and based on this garbage program determines how much memory it should allocate for list copying. 并且在此复制过程中,您可能会得到std :: bad_alloc,因为复制列表涉及内存分配,并且可能原始列表已被破坏,因此指向原始列表的指针指向了一些随机垃圾,并根据此垃圾程序确定了该内存应该多少分配用于列表复制。 So ensure that your original list is still alive. 因此,请确保您的原始列表仍然有效。

Or fix your code like this: List& My_List = *ls and get a crash somewhere later. 或像这样修复您的代码: List& My_List = *ls ,稍后再崩溃。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM