Как правильно инициализировать ссылочный член объекта, чтобы его значение оставалось после выхода из конструктора объекта? - PullRequest
0 голосов
/ 02 апреля 2019

В приведенном ниже коде после использования инициализатора 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!
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...