【发布时间】:2020-12-05 00:34:30
【问题描述】:
我正在学习拷贝构造函数和浅拷贝和深拷贝。我在关注这个视频:Copying and Copy Constructors in C++
以下代码是直接从视频中复制过来的,演示了浅拷贝……(视频中9点30分)
这段代码应该在运行后崩溃,因为解构器会尝试两次释放相同的内存(第一次是string,后来是string2)。第一次删除应该可以正常工作,但第二次删除应该会导致程序崩溃,因为我们正在尝试删除未分配的内存。
令人惊讶的是,我的情况并没有发生这种情况。我在命令提示符下使用g++ copying_and_copy_constructor.cpp 编译了代码,它编译良好并使用a.exe 运行它。没有错误。
#include<iostream>
#include<cstring>
#include<string>
using std::endl;
using std::cout;
class String
{
private:
char* m_Buffer;
unsigned int m_size;
public:
String(const char* string)
{
m_size = strlen(string);
m_Buffer = new char[m_size+1];
memcpy(m_Buffer,string,m_size);
m_Buffer[m_size] = 0;
}
~String()
{
delete [] m_Buffer;
}
friend std::ostream& operator << (std::ostream& stream, const String& string);
};
std::ostream& operator<<(std::ostream& stream, const String& string)
{
stream<< string.m_Buffer;
return stream;
}
int main()
{
String string = "My string";
String string2 = string;
cout<<string2<<endl;
cout<<string;
return 0;
}
我什至尝试检查调试器。我使用g++ -g copying_and_copy_constructor.cpp 编译代码,然后使用gdb a.exe。这是它的输出:
GNU gdb (GDB) 7.6.1
Copyright (C) 2013 Free Software Foundation, Inc.
License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>
This is free software: you are free to change and redistribute it.
There is NO WARRANTY, to the extent permitted by law. Type "show copying"
and "show warranty" for details.
This GDB was configured as "mingw32".
For bug reporting instructions, please see:
<http://www.gnu.org/software/gdb/bugs/>...
Reading symbols from D:\a.exe...done.
(gdb) start
Temporary breakpoint 1 at 0x401446: file copying_and_copy_constructor.cpp, line 43.
Starting program: D:\a.exe
[New Thread 44892.0x8258]
[New Thread 44892.0x6df8]
[New Thread 44892.0xadd8]
[New Thread 44892.0x9658]
Temporary breakpoint 1, main () at copying_and_copy_constructor.cpp:43
43 String string = "My string";
(gdb) c
Continuing.
My string
My string[Inferior 1 (process 44892) exited normally]
(gdb)
The program is not being run.
(gdb) q
这条线让我很困惑My string[Inferior 1 (process 44892) exited normally]。这段代码如何正常退出?
视频中的人正在使用 VS-Code...我如何在命令提示符下得到同样的错误?
(我现在没有vs代码(以后可能会安装))
【问题讨论】:
-
未定义的行为可能导致任何事情,包括明显的良好功能。不保证崩溃。
-
哦...我以为我使用 gdb 错误或类似的东西。那么调试这些错误一定是一场噩梦:(
-
@Yatin 这就是为什么你需要一个好的调试器。更好的调试器比更好的编译器更好。
标签: c++ debugging visual-studio-code gdb shallow-copy