• 카테고리

    질문 & 답변
  • 세부 분야

    프로그래밍 언어

  • 해결 여부

    미해결

초급한 질문이라 죄송합니다.

19.02.23 14:25 작성 조회수 146

0

우선 강의 중 몇분 몇초 부분이라 정하기 어려운 질문입니다 ㅠ

고민을 아무리 해봐도 답을 찾이 못해서 남깁니다.

입출력연산자 오버로딩에서 아래와 같이 const 를 빼고 Cents &cents 로 받으면

std::ostream &operator << (std::ostream &out, Cents &cents)

단항 연산자가 붙지 않으면 cout << cents1 << endl; 는 출력이 되고

cout << -cents1 << endl; 는 왜 출력이 안될까요?ㅠ

const 쪽 강의를 다시 들어도,, 디버거로 찍어보며 천천히 따라가도 이유를 모르겠어서 질문 남깁니다 .

감사합니다.

답변 5

·

답변을 작성해보세요.

2

skf346님의 프로필

skf346

2022.10.14

윗 분 말씀처럼 rvalue와 관련이 있습니다.

-cents는 Cents(-m_cents)를 return하는데 이건 익명 객체이죠. 익명 객체(Cents(10) 등)는 rvalue로 여겨지는데 함수로 pass rvalue를 하려면 parameter는 const reference만 가능합니다.

rvalue를 왜 const reference로만 받아야 하는가에 대해서는 아래 링크에 설명되어있습니다.

https://stackoverflow.com/questions/36102728/why-is-it-allowed-to-pass-r-values-by-const-reference-but-not-by-normal-referenc?newreg=af09de2f1d8d479ca830d2af2a5cb732

한 가지 예시가 나오는데

void display(int& a) { a = 10 };

display(1);

가 있다면 말 그대로 a = 10은 rvalue에 rvalue를 넣으라는 말입니다. 말이 안되죠.

따라서 질문자님이 말씀하신 reference만 사용할 수 없습니다

그럼 왜 const가 이 역할을 하는가는 c++의 feature로 인한것 같습니다.

Q1: Is the following code legal C++?

// Example 1

string f() { return "abc"; }

void g() {
const string& s = f();
  cout << s << endl;    // can we still use the "temporary" object?
}

A1: Yes.

This is a C++ feature… the code is valid and does exactly what it appears to do.

Normally, a temporary object lasts only until the end of the full expression in which it appears. However, C++ deliberately specifies that binding a temporary object to a reference to const on the stack lengthens the lifetime of the temporary to the lifetime of the reference itself, and thus avoids what would otherwise be a common dangling-reference error. In the example above, the temporary returned by f() lives until the closing curly brace. (Note this only applies to stack-based references. It doesn’t work for references that are members of objects.)

Does this work in practice? Yes, it works on all compilers I tried (except Digital Mars 8.50, so I sent a bug report to Walter to rattle his cage :-) and he quickly fixed it for the Digital Mars 8.51.0 beta).

Q2: What if we take out the const… is Example 2 still legal C++?

// Example 2

string f() { return "abc"; }

void g() {
string& s = f();       // still legal?
  cout << s << endl;
}

A2: No.

The "const" is important. The first line is an error and the code won’t compile portably with this reference to non-const, because f() returns a temporary object (i.e., rvalue) and only lvalues can be bound to references to non-const.

요약하자면 const reference는 temporary object(rvalue)의 수명을 연장시켜 준다고 합니다. reference로만 받았을 때는 그 수명이 해당 expression에만 머물러 문제가 발생합니다.

덕분에 저도 찾아보면서 많은 공부가 되었습니다!

혹시 잘못된 내용있으면 답변으로 수정 부탁드립니다.

2

쭌랩님의 프로필

쭌랩

2019.02.24

컴파일 단계부터 오류가 생기더라구요 ㅠ 오류가 생기는 이유를 모르겠습니다.ㅠㅠ - 가 연산자 인것과 const를 붙이는 것과의 연관성을 모르겠습니다. const는 그 영역 안에서 변수가 바뀔 일이 없을때 붙여주는것으로 알고있는데 붙이지 않아도 컴파일 단계오류는 생기면 안되지 않나요?ㅠ

1

thd2tn님의 프로필

thd2tn

2022.09.15

6.15 강의를 보시면 더 자세하게 알 수 있으실 거 같은데 Cents& cents는 literal로는 초기화가 안되지만 const Cents& cents는 literal로 초기화가 될 수 있어서 발생하는 문제인 거 같습니다.

0

호두님의 프로필

호두

2020.01.16

김준성님 이 문제 혹시 해결하셨나요? 

0

-cents1할 때 -도 연산자라서 오퍼레이터 오버로딩을 해줘야할텐데, 컴파일할때 오류가 안생겼었나요?