c++ 동적할당

강효림·2023년 5월 15일
0

c++

목록 보기
7/8

동적할당

Student(int _number, string _name, string _adress) 
		: number(_number), name(_name), adress(_adress)
{
}
...
int main(){
	Student* std3 = new Student(1111, "김민지", "서울");
    

동적할당(new)을 하면 const/참조형 멤버변수를 사용가능하다.
동적할당된 공간은 포인터로 접근해야한다.
멤버함수를 가리킬때는 ->을 사용한다.
ex ) std3->print();

동적할당을 하면 반드시 해제(delete)를 해줘야한다.
메모리절약을 위해서다.

int main(){
	Student* std3 = new Student(1111, "김민지", "서울");
    
    delete std3;

객체배열 동적할당

Student* std4 = new Student[2];
for(int i = 0; i<2; i++){
	std4[i].print();
}
delete[] std4;

배열요소에 해당하는 객체멤버에 포인터를 사용할 때는 ->를 사용할 수 없다. .으로 접근해야한다.

멤버변수 동적할당

#include <iostream>
#include <string.h>

using namespace std;

class MString {
public :
	MString(const char* str) {
		unsigned int l = strlen(str);
		c_str_ = new char[l+1];  //'\0'(널문자)가 들어갈 공간 +1
		strcpy(c_str_, str);
	}
	char* c_str(void) {
		return c_str_; //_(언더 스코어) 멤버변수라는 뜻
	}
private:
	char* c_str_; //문자열의 시작주소
};

int main() {
	MString* str = new MString("I will be back");
	cout << str->c_str() << endl;
	return 0;
}

I will be back

strlen으로 길이를 l에 저장하고
c_str_이라는 char배열을 만든다.
strcpystr의 값을 c_str_로 복사한다.
strc_str을 가리켜 호출하고 변수 c_str_을 리턴해 메인에서 출력하게 한다.

소멸자

~ 기호는 소멸자를 나타낸다.
소멸자로 생성자에서 동적할당한 메모리를 메모리 누수 방지를 위해 해제해준다. 소멸자를 쓰면 객체만 삭제될 뿐 동적할당으로 생성된 문자열은 남아있다.

class MString {
public :
	~MString() {
		delete[] c_str_;
	}
};

0개의 댓글