免责声明: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;
};
最佳答案
正如约翰所说,删除对象的拷贝没问题。它崩溃是因为您正在返回对局部变量 ( tmp
) 的引用。当函数返回时,这个对象不再存在,所以你不能使用它。更改 T & SomeQueue<T>::dequeue
进入T SomeQueue<T>::dequeue
所以你返回一个 T
的拷贝对象,而不是引用。
(而且,如果您在编译时启用警告,大多数编译器都会告诉您此类事情)。
关于c++返回保存在已删除动态对象中的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19195374/