[英]initialization of ints vs initialization of strings using pointers, c++
I recently ran into an issue while experimenting with linked lists. 我最近在尝试链接列表时遇到了一个问题。 When I use a function to link up a new node that has a string in its data field it doesn't work.
当我使用函数链接一个新节点时,该节点的数据字段中包含一个字符串,它不起作用。 By this I mean that when the function (linkin() see below) returns , the string (which was local to the function) is destroyed and so the string field appears to be uninitialized.
我的意思是,当函数(linkin()见下文)返回时,字符串(在函数本地)被破坏,因此字符串字段似乎未初始化。
However, when I do this exact same operation with an int it seems to work just fine. 但是,当我使用int进行此完全相同的操作时,它似乎正常工作。 The code I used is below (its the int version, but make val a string instead of an int to see the other version).
我使用的代码如下(其int版本,但将val改为字符串而不是int以查看其他版本)。 Could someone explain to me what is happening?
有人可以向我解释发生了什么吗?
Thanks! 谢谢!
struct testlist {
int val;
testlist *next;
};
void linkin ( testlist *a );
int main() {
testlist test;
linkin(&test);
cout << test.next->val <<endl;
}
void linkin ( testlist *a )
{
testlist b;
b.val=1;
a->next = &b;
cout << a->next->val <<endl;
}
testlist b;
a->next = &b;
a->next
is pointing to a local temporary object which will be destroyed right after returning from function. a->next
指向一个本地临时对象,该对象将从函数返回后立即销毁。 It invokes undefined behavior after dereferencing it out of the function. 从函数中取消引用未定义的行为后,它将调用它。
It's undefined behavior, sometimes it works, sometimes not. 这是未定义的行为,有时有效,有时无效。
Also in C++ there is a linked-list: std::list
. 同样在C ++中,有一个链表:
std::list
。 On the other hand, you can use smart-pointers such as std::unique_ptr
instead of bare pointers. 另一方面,您可以使用诸如
std::unique_ptr
类的智能指针来代替裸指针。 I've written a smart-pointer based of your container: 我已经根据您的容器编写了一个智能指针:
struct List
{
int val;
unique_ptr<List> next;
};
void linkin (List &a)
{
unique_ptr<List> b(new List);
b->val = 1;
a.next = move(b); // After move you can't use b anymore
cout << a.next->val << endl;
}
int main()
{
List test;
linkin(test);
cout << test.next->val <<endl;
}
Straight away, in linkin()
I can see you're storing a pointer in a
to an object that is going to go out of scope - ie: be destroyed. 马上,在
linkin()
我可以看到你存储在一个指针a
到将要超出范围的对象-即:被破坏。
There are reasons why this might appear to work with an int but not a complex type like a std::string. 有一些原因可能使它看起来像int而不适用于std :: string之类的复杂类型。 Despite appearances this is broken code - try rewriting
linkin()
: 尽管出现了这种情况,但代码已损坏-尝试重写
linkin()
:
void linkin ( testlist& a )
{
testlist* b = new testlist;
b->val=1;
a->next = b;
cout << a->next->val <<endl;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.