inflearn logo
강의

강의

N
챌린지

챌린지

멘토링

멘토링

N
클립

클립

로드맵

로드맵

지식공유

홍정모의 따라하며 배우는 C++

10.6 컨테이너 클래스

클래스 리턴값 관련 질문

244

twinlove11

작성한 질문수 3

0

안녕하세요! 연습문제 구현하다가 궁금한 점이 생겨 질문드립니다.

클래스를 리턴값으로 받는 멤버변수를 여러개 만들다보니 실수하여 &(참조)를 빼먹으니까 retunr 0;을 만나기도 전이었는데 멤버함수가 리터값을 받자마자 바로 소멸자를 호출하더라구요.

&를 넣으면 문제없이 빌드됩니다.  왜 바로 소멸자를 호출하는지 이해가 안됩니다ㅠㅠ 

< &(참조)를 붙인 상황>

IntArray& remove(const int & ix) // arr[3]

{

//1 10 3 5 7 9

//1 10 3 7 9

 

for (int a = ix; a < m_length - 1; a++)

m_data[a] = m_data[a + 1];

resize(m_length - 1);

 

return *this;

}

 

< &(참조)가 없는 상황>

IntArray remove(const int & ix) // arr[3]

{

//1 10 3 5 7 9

//1 10 3 7 9

 

for (int a = ix; a < m_length - 1; a++)

m_data[a] = m_data[a + 1];

resize(m_length - 1);

 

        return *this;

}

C++

답변 1

1

강민철

안녕하세요 :)

아래처럼 

참조자 없이도 연습문제 구현은 가능합니다.

#include <iostream>

class IntArray {
  int * m_data = nullptr;
  unsigned m_length = 0;

  public:
    IntArray(unsigned length = 0) {
      initialize(length);
    }

  IntArray(const std::initializer_list < int > & list) {
      initialize(list.size());
      int count = 0;
      for (auto & e: list)
        m_data[count++] = e;
    }

    ~IntArray() {
      delete[] m_data;
    }

  void initialize(unsigned length) {
    m_length = length;
    if (m_length > 0)
      m_data = new int[m_length];
  }

  void reset() {
    if (m_data) {
      delete[] m_data;
      m_data = nullptr;
    }
    m_length = 0;
  }

  void resize(const unsigned & length) {
    if (length == 0)
      reset();
    else if (m_length < length) {
      int * new_m_data = new int[length];
      for (unsigned i = 0; i < m_length; ++i)
        new_m_data[i] = m_data[i];
      delete[] m_data;
      m_data = new_m_data;
    }
    m_length = length;
  }

  void insertBefore(const int & value,
    const int & ix) {
    resize(m_length + 1);
    for (int i = m_length - 2; i >= ix; --i)
      m_data[i + 1] = m_data[i];
    m_data[ix] = value;
  }

  void remove(const int & ix) {
    for (int i = ix; i < m_length - 1; ++i)
      m_data[i] = m_data[i + 1];
    --m_length;
    if (m_length <= 0)
      reset();
  }

  void push_back(const int & value) {
    insertBefore(value, m_length);
  }

  friend std::ostream & operator << (std::ostream & out,
    const IntArray & arr) {
    for (unsigned i = 0; i < arr.m_length; ++i)
      out << arr.m_data[i] << ' ';
    return out;
  }
};

int main() {
  using namespace std;

  IntArray my_arr { 1, 3, 5, 7, 9 };
  cout << my_arr << endl;

  my_arr.insertBefore(10, 1);
  cout << my_arr << endl;

  my_arr.remove(3);
  cout << my_arr << endl;

  my_arr.push_back(13);
  cout << my_arr << endl;
}

 

문제가 발생한 전체 소스코드를 첨부해주시면 보다 명확하게 문제를 말씀드리겠습니다 :)

감사합니다. 

새해 복 많이 받으세요 :)

 

0

twinlove11

#include <iostream>

#include <array>

using namespace std;

 

class IntArray

{

private:

int m_length = 0;

int *m_data = nullptr;

 

public:

IntArray(const int length)

: m_length(length)

{

m_data = new int[length];

}

 

IntArray(const std::initializer_list<int> &list)

: IntArray(list.size())

{

int count = 0;

for (auto & element : list)

{

m_data[count] = element;

++count;

}

 

}

 

void reset()

{

delete[] this->m_data;

this->m_length = 0;

}

 

IntArray& resize(const int & length_in)

{

if (m_length == length_in)

{

return *this;

}

else if (m_length < length_in) 

{

int *temp = new int[length_in];

 

for (int a = 0; a < m_length; ++a)

temp[a] = m_data[a];

for (int a = m_length; a < length_in; ++a)

temp[a] = 0;

 

m_length = length_in;

delete[] m_data;

m_data = temp;

}

else 

{

m_length = length_in;

int *temp = new int[length_in];

for (int i = 0; i < m_length; ++i)

{

temp[i] = m_data[i];

}

 

m_length = length_in;

delete[] m_data;

m_data = temp;

}

return *this;

}

 

IntArray& insertBefore(const int & value, const int & ix)

{

resize(m_length + 1);

 

for (int a = m_length - 1; a > ix; a--)

{

m_data[a] = m_data[a - 1];

}

for (int a = 0; a < m_length; ++a)

{

cout << m_data[a] << " ";

}

 

m_data[ix] = value;

 

return *this;

}

//*********************

IntArray remove(const int & ix)

{

for (int a = ix; a < m_length - 1; a++)

m_data[a] = m_data[a + 1];

resize(m_length - 1);

 

return *this;

}

IntArray& push_back(const int & ix)  

{

resize(m_length + 1);

m_data[m_length - 1] = ix;

 

return *this;

}

 

friend ostream& operator << (ostream & out, const IntArray & int_arr)

{

for (int i = 0; i < int_arr.m_length; i++)

out << int_arr.m_data[i] << " ";

 

return out;

}

 

~IntArray()

{

delete[] m_data;

}

 

};

 

int main()

{

IntArray my_arr{ 1,3,5,7,9 };

cout << my_arr << endl;

my_arr.insertBefore(10, 1);

cout << my_arr << endl;

my_arr.remove(3);

cout << my_arr << endl;

my_arr.push_back(13);

cout << my_arr << endl;

 

return 0;

}

IntArray로 리턴값을 받는 부분(//******** 으로 표시한 코드) 보시면 참조자 없이 디버깅 해보면  return *this 가 끝나면 소멸자를 호출하는데 참조자가 있을 경우엔 소멸자가 호출이 안되고 정상적으로 잘 작동합니다. 혹시 어떤 원리인지 알 수 있을까요??

0

강민철

작성해주신 위 코드의 경우, 참조자가 있어야 소멸자가 호출됩니다.

참조자 리턴하는 것은 연산을 수행하는 객체 그 자체를 리턴하는 것이고,

참조자 없이 리턴하는 것은 객체의 사본을 리턴합니다.

참조자 없이 리턴한 객체는 소멸자의 대상이 아닙니다.

 

즉, 참조자로 리턴하셔야 소멸자의 대상이 되기 때문에

참조자로 리턴하셔야 해당 객체에 대한 소멸자가 호출 됩니다.

(insertBefore, push_back에서 참조자를 빼면 빌드 오류가 발생하는 것과 같은 이유입니다.)

 

추가 질문이 있으시다면 편하게 댓글 달아주세요! :)

감사합니다.

 

변수가 메모리에 저장되는 것을 알려주는 강의가 어떤강의였죠

1

481

1

메모리 주소 10진수로 출력

1

672

1

클래스 템플릿 특수화에서 boolalpha로 표현된 리턴값에 대해 질문이 있습니다.

1

515

1

여러가지 리턴 타입에 관한 강의가 어떤 걸까요?

1

549

1

메모리 주소에 관한 질분

0

687

1

인터페이스 클래스에서 reportError의 매개변수에 대해 궁금한 것이 있습니다.

0

558

1

형변환 오버로딩에서 const 관련 질문이 있습니다.

0

448

1

Digit 뒤에 reference를 사용하는 이유

0

512

1

4.2 전역 변수, 정적 변수, 내부 연결, 외부 연결

0

325

1

dat파일이...

0

540

1

TODO:대입 연산자 오버로딩에 대한 소스코드입니다.

0

651

1

복사 생성자 관련 질문이 있습니다.

0

456

1

수업 중 궁금한점이 있습니다.

1

392

1

라이브러리자체가 이해가 되지 않습니다.

0

565

1

마지막 예제 질문

0

305

1

증감연산자 위치에 따른 수행 순서 질문입니다.

0

382

1

단항 연산자 오버로딩에서 return 부분에 질문이 있습니다.

1

416

1

friend함수 관련 질문이 있습니다.

0

313

1

operator+ 정의부분에서 궁금한 것이 있습니다.

0

448

1

3분 17초 질문

0

354

1

함수에 값을 대입한다는 개념이 이해가 되지 않습니다.

0

450

1

int getvalue() const에서 const는 왜 뒤에 붙는건가요?

0

453

2

const Something &st에서 const를 빼면 안되나요?

0

304

1

friend함수는 다른 클래스의 멤버함수로 쓸 수 없나요??

1

495

1