首页 > 解决方案 > 如何正确初始化对象的引用成员,以便在对象构造函数退出后保留其值?

问题描述

在下面的代码中使用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!

标签: c++reference

解决方案


推荐阅读