TIL::Today I Learn

[TIL] 20230621

madylin 2023. 6. 22. 15:53
반응형

오늘 공부한 내용📓

- C++

함수 공부

new

포인터 변수명 = new 타입;
//int *ptr = new int;
포인터 변수명{new 타입};
//int *ptr{new int};

//초기화 같이 하는 방법
포인터 변수명 = new 타입(초기화 값);
//int *ptr = new int(10);
포인터 변수명{new 타입};
//int *ptr{new int(10)};
  • 메모리 공간 할당하는 연산자이며, 생성자를 호출하고, 할당하고자 하는 자료형에 맞게 형 변환
  • new 는 바로 초기화가 가능함
  • 메모리 할당 실패 시, malloc 과는 다르게 bad_alloc 이라는 익셉션을 리턴함. try - catch 문을 사용해서 확인해야 한다.
#include <iostream>
int main()
{
	try
	{
		int *ptr = new int;
	}
	catch (std::bad_alloc & ba)
	{
		std::cerr << "bad_alloc 발생" << ba.what() << std::endl;
	}
	return 0;
}
  • nothrow 를 사용해서 익셉션 대신 nullptr 을 리턴하도록 할 수 있음
#include <new>
#include <iostream>
int main()
{
	int *ptr = new(std::nothrow) int;
	if (ptr == nullptr)
		std::cout << "return nullptr" << std::endl;
	return 0;
}

 

제가 공부한 내용을 기록하고 있습니다.

혹시 수정이 필요한 부분이 있다면, 댓글로 지적 부탁드립니다!

선한 관심과 도움 감사드립니다😊

반응형

'TIL::Today I Learn' 카테고리의 다른 글

[TIL] 20230704  (0) 2023.07.06
[TIL] 20230622  (0) 2023.06.24
[TIL] 20230620  (0) 2023.06.21
[TIL]20230619  (0) 2023.06.20
[TIL] 20230618  (0) 2023.06.19