0

免责声明:Java 开发人员学习 C++。

当您返回保存在已删除动态对象中的字符串时会发生什么?

这是一个相当标准的出队方法,我想让它在使用模板数据指针的情况下工作,这是我的测试用例中的一个字符串。

Ubuntu 13.04 上的 g++ 给了我段错误。在最新的 OSX 上,我的数据已损坏。

是我的代码还是 C++?

// remove an object from the front of the queue.
// the test case instantiate T as string. 
// front->data is assigned an static string.
template<class T>
T & SomeQueue<T>::dequeue() {
    if (empty()) throw runtime_error("kaboom");

    T tmp = front->data;
    Node<T> *n = front;
    front = front->next;
    delete n;

    return tmp;
};
4

3 回答 3

4

As john says, the copy of the deleted object is fine. It crashes because you are returning a reference to a local variable (tmp). When the function returns, this object no longer exists, so you can't use it. Change T & SomeQueue<T>::dequeue into T SomeQueue<T>::dequeue so you return a copy of a T object, rather than a reference.

(And, if you enable warnings when you compile, most compilers will tell you about this sort of thing).

于 2013-10-05T07:56:36.707 回答
3

这段代码没问题,因为您在删除对象之前复制了字符串。段错误的原因是别的。

更正:

问题就在这里

template<class T>
T & SomeQueue<T>::dequeue() {

应该

template<class T>
T SomeQueue<T>::dequeue() {

不要返回对局部变量的引用。局部变量被破坏了,这就是给你一个已经被破坏的东西的引用。

于 2013-10-05T07:55:02.490 回答
3

That code is just fine, the reason for segfault is that you are returning a reference to a local variable which gets destroyed upon function exit.

T tmp = front->data;
Node<T> *n = front;
front = front->next;
delete n;

return tmp; //tmp is a local variable here. You are returning a reference (T&)
于 2013-10-05T07:56:45.740 回答