#include <iostream>

using namespace std;

struct TestStruct {
public:
	TestStruct(const int _num, const int _cnum, int* _pnum) : num(_num), cnum(_cnum), pnum(_pnum) {}
	~TestStruct() {
		if (nullptr != pnum) {
			delete pnum;
			pnum = nullptr;
		}
	}

private:
	int num;
	const int cnum;
	int* pnum;
};

int main() {
	FILE* pWriteFile = nullptr;
	if (errno_t err = fopen_s(&pWriteFile, "../Data/test.bin", "wb"))
		return 0;

	TestStruct* pTest1 = new TestStruct(10, 20, new int(30));

	fwrite(pTest1, sizeof(TestStruct), 1, pWriteFile);
	fclose(pWriteFile);

	delete pTest1;
	pTest1 = nullptr;

	/* ---------------- */

	FILE* pReadFile = nullptr;
	if (errno_t err = fopen_s(&pReadFile, "../Data/test.bin", "rb"))
		return 0;

	TestStruct* pTest2 = new TestStruct(50, 60, nullptr);

	fread(pTest2, sizeof(TestStruct), 1, pReadFile); // const 멤버 변수가 있는데 어떻게 가능한지
	fclose(pReadFile);

	delete pTest2;
	pTest2 = nullptr;

	return 0;
}

 

구조체 멤버변수 cnum은 const라서 초기화 이후 수정이 되면 안되는데 fread를 통해 스트림의 데이터를 구조체 크기만큼 덮어쓰니까 에러가 발생하지 않고 값이 바뀌어버림.

 

포인터나 레퍼런스가 아니라서 const_cast가 적용될리도 없고 애초에 c함수라서 const_cast가 존재하지 않음

대체 왜..?

'프로그래밍 > 공부' 카테고리의 다른 글

선언과 정의의 차이  (0) 2022.09.28
[자료구조] 힙  (0) 2022.07.23
[자료구조] 트리, 그래프  (0) 2022.07.23
Effective C++ [4] 설계 및 선언  (0) 2015.07.10
Effective C++ [3] 자원관리  (0) 2015.07.09

+ Recent posts