c++ - C++ 复制构造函数错误地接受参数
问题描述
我有以下行为奇怪的代码。到目前为止我理解的流程是,display(line);
将调用复制构造函数Line::Line(const Line &obj)
,并将line
传入的引用。但是cout<<"[origin] *ptr="<<*obj.ptr<<endl;
将打印[origin] *ptr=32767
而不是[origin] *ptr=10
。
更奇怪的是,如果我取消注释// int x=3;
,它会正确打印,但我真的不知道为什么。
您可以在以下位置找到可执行代码:https ://www.onlinegdb.com/pjbPO0X1f
#include <iostream>
using namespace std;
class Line
{
public:
int getLength( void );
Line( int len );
Line( const Line &obj);
private:
int *ptr;
};
// constructor
Line::Line(int len)
{
ptr=&len;
cout<<"*ptr="<<(*ptr)<<endl;
}
// copy constructor
Line::Line(const Line &obj)
{
// int x=3;
cout<<"[origin] *ptr="<<*obj.ptr<<endl;
ptr = new int;
*ptr = *obj.ptr; // copy
}
int Line::getLength( void )
{
return *ptr;
}
void display(Line obj)
{
cout << "line=" << obj.getLength() <<endl;
}
int main( )
{
Line line(10);
display(line);
return 0;
}
解决方案
您的程序调用未定义的行为(UB)。当您的构造函数完成时:
Line::Line(int len)
{
ptr=&len;
cout<<"*ptr="<<(*ptr)<<endl;
} // ptr is dangling
指针ptr
指向一个len
不再存在的局部变量。ptr
现在悬空,并且任何取消引用它的尝试都会调用 UB。
你的程序可以做任何事情。您还可以看到一些奇怪的结果,例如添加int x = 3
导致您的程序“行为正确”。不要担心为什么会发生这种情况,这只是UB的结果。
推荐阅读
- javascript - 如何更改 Fancybox 3 中的控制栏颜色?
- sql - 在 BigQuery 表中展平多个相同大小的数组列
- php - 如何配置 Symfony 工作流程
- tkinter - 框架/画布中不同小部件的滚动条
- mysql - 具有相关列值的表的最佳数据库表设计
- javascript - 如何使用 javascript 检查产品是否为空 Laravel
- salesforce - 如何在 Salesforce 中创建自定义错误页面
- r - 在ggplot中用组在点之间画线
- android - 使用“react-native-firebase v6”将数据从通知传递到它打开的应用程序的最佳方法是什么?
- csv - 有没有一种简单的方法可以将镶木地板文件直接加载到 Cassandra 中?