static_cast를 이용해서 형변환시 형에 관련하여 질문드립니다.

renboy의 이미지

안녕하세요.

현재 Effective c++로 공부중에 있습니다.

const 관련부를 공부하다가 비상수 객체를 상수 객체로 변경하는 부분인데요.

클래스명은 CMyString 입니다.
하나의 함수는 const char& operator[](int nIndex) const 이구요.
하나의 함수는 char& operator[](int nIndex) 입니다.

char& operator[](int nIndex) 함수 내에서
const char& operator[](int nIndex) const 함수를 호출하기 위해서
객체를 형변환 해주는데요.

그 부분이 (static_cast<const CMyString&>(*this))[0]; 입니다.

여기서 제가 궁금한 점은
형을 꼭 <const CMyString&>으로해줘야 하는 것인지 입니다.

제가 그냥 <const CMyString> 으로만 해서 이것 저것 테스트를 해보았으나
전혀 다른점을 못 찾겠거든요..

형을 <const CMyString&>으로 해준것과 <const CMyString>으로 한 것과 차이점이 궁금합니다.

바쁘신 와중에 수고스럽겠지만 답변 부탁드리겠습니다.

감사합니다.

 의 이미지

#include <iostream>
#include <iomanip>
using namespace std;
 
static void print_addr(const char *type, const void *p){
	cout << right << setfill(' ');
	cout << setw(32) << type << ": ";
	cout << left << "I'm " << p << endl;
}
 
class with_ref{
public:
	void whoami(void) const{
		print_addr(__PRETTY_FUNCTION__, this);
	}
	void whoami(void){
		print_addr(__PRETTY_FUNCTION__, this);
		static_cast<const with_ref &>(*this).whoami();
	}
};
 
class without_ref{
public:
	void whoami(void) const{
		print_addr(__PRETTY_FUNCTION__, this);
	}
	void whoami(void){
		print_addr(__PRETTY_FUNCTION__, this);
		static_cast<const without_ref>(*this).whoami();
	}
};
 
int main() {
	with_ref with_ref_inst;
	with_ref_inst.whoami();
 
	without_ref without_ref_inst;
	without_ref_inst.whoami();
	return 0;
}

         void with_ref::whoami(): I'm 0x7ffdcfb6d0cd
   void with_ref::whoami() const: I'm 0x7ffdcfb6d0cd
      void without_ref::whoami(): I'm 0x7ffdcfb6d0ce
void without_ref::whoami() const: I'm 0x7ffdcfb6d0cf

https://ideone.com/iMCVal

귀하와 같이 스스로 생각하고 탐구할 수 있는 지성이라면 예제 코드와 예시 출력 한 쌍으로 충분한 답이 되겠지요.

참고: __PRETTY_FUNCTION__는 gcc Extensions으로, 표준이 아닙니다.
출력 편의상 사용했을 뿐이고 질문의 논점과 관계 없습니다.

https://gcc.gnu.org/onlinedocs/gcc/Function-Names.html

renboy의 이미지

자세한 답변 감사드립니다.

아 참조형으로 캐스팅을 하지 않을 경우에는
without_ref_inst 객체의 whoami const가 아니라 임시 객체(?)의 whoami const가 호출되는 것이군요.

명쾌한 예시 너무나 감사드립니다!! 선생님.^^

댓글 달기

Filtered HTML

  • 텍스트에 BBCode 태그를 사용할 수 있습니다. URL은 자동으로 링크 됩니다.
  • 사용할 수 있는 HTML 태그: <p><div><span><br><a><em><strong><del><ins><b><i><u><s><pre><code><cite><blockquote><ul><ol><li><dl><dt><dd><table><tr><td><th><thead><tbody><h1><h2><h3><h4><h5><h6><img><embed><object><param><hr>
  • 다음 태그를 이용하여 소스 코드 구문 강조를 할 수 있습니다: <code>, <blockcode>, <apache>, <applescript>, <autoconf>, <awk>, <bash>, <c>, <cpp>, <css>, <diff>, <drupal5>, <drupal6>, <gdb>, <html>, <html5>, <java>, <javascript>, <ldif>, <lua>, <make>, <mysql>, <perl>, <perl6>, <php>, <pgsql>, <proftpd>, <python>, <reg>, <spec>, <ruby>. 지원하는 태그 형식: <foo>, [foo].
  • web 주소와/이메일 주소를 클릭할 수 있는 링크로 자동으로 바꿉니다.
댓글 첨부 파일
이 댓글에 이미지나 파일을 업로드 합니다.
파일 크기는 8 MB보다 작아야 합니다.
허용할 파일 형식: txt pdf doc xls gif jpg jpeg mp3 png rar zip.
CAPTCHA
이것은 자동으로 스팸을 올리는 것을 막기 위해서 제공됩니다.