c++ - 如何正确初始化对象的引用成员,以便在对象构造函数退出后保留其值?
问题描述
在下面的代码中使用bar
初始化器后,值集不是Foo
构造函数结束后存储的值。
#include <iostream>
using namespace std;
const int a = 2;
class Bar
{
public:
int getLength(void);
Bar(const int &len); // simple constructor
Bar(const Bar &obj); // copy constructor
~Bar(); // destructor
private:
int *ptr;
};
void display(Bar obj);
class Foo
{
public:
const Bar &bar;
Foo() : bar(a)
{
};
};
Bar::Bar(const int &len)
{
cout << "Normal constructor allocating ptr" << endl;
ptr = new int;
*ptr = len;
}
Bar::Bar(const Bar &obj)
{
cout << "Copy constructor allocating ptr." << endl;
ptr = new int;
*ptr = *obj.ptr; // copy the value
}
Bar::~Bar(void)
{
cout << "Freeing memory!" << endl;
delete ptr;
}
int Bar::getLength(void)
{
return *ptr;
}
void display(Bar obj)
{
cout << "Length of bar : " << obj.getLength() << endl;
}
int main()
{
Bar bar(10);
Foo foo;
display(foo.bar);
return 0;
}
如何仍然使用引用变量bar
来解决这个问题?
实际输出
Normal constructor allocating ptr
Normal constructor allocating ptr
Freeing memory!
Copy constructor allocating ptr.
Length of bar : 16407632
Freeing memory!
Freeing memory!
所需输出
Normal constructor allocating ptr
Normal constructor allocating ptr
Freeing memory!
Copy constructor allocating ptr.
Length of bar : 2
Freeing memory!
Freeing memory!
解决方案
推荐阅读
- braintree - 如何在 UI 中的 Braintree 的 dropin 中编辑卡片?
- python - python:如何不断更新QGridLayout中的按钮
- c# - System.ArgumentOutOfRangeException: '索引超出范围。从一个列表复制到另一个
- python - 数据未存储在数据库中用于 UserRegsitrationForm django 的选择字段
- python - 使用 Python 的 API 从谷歌驱动器中删除文件/文件夹
- python-3.x - Python BeautifulSoup 正则表达式过滤器不起作用
- php - 如何通过PHP删除字符串中的特殊字符“?
- mysql - 我们如何在另一个表中使用主键
- java - 为什么我的扩展 android.app.application 的应用程序类不起作用?
- laravel - Laravel 社交名流