Rylah's Study & Daily Life

Modern C++ : 02. Memory Structure - 객체 생성, Object Creation 본문

Study/C++

Modern C++ : 02. Memory Structure - 객체 생성, Object Creation

Rylah 2022. 2. 3. 13:11

Object

 - Objct create, new / Java -> C++ (습관적으로 new를 사용함)

 

Modern C++

pointer -> new object.

Smart Pointer use

#include <iostream>
#include <vector>


class Person
{
public:
	Person(std::string name, int age)
		:name(std::move(name)), age(age) {};
private:
	std::string name;
	int age;
};

int main(void)
{
	Person a("nocope", 31); // Stack에 우선시

	// Person * ap = new Person(); // Heap 
	// delete ap;
	std::vector<Person> people; // Heap use smartpointer STL vector
}

 Stack으로 생성하면 Fuction이 지나며 stack 특성상 자동으로 소멸된다.

 

 Heap으로 특히 new로 선언하게 되면 delete를 해주지 않게 되면 안된다.

 

대신 heap을 이용하면 범위에서 자유로운 포인터를 활용할 수 있으므로 장점이 없지는 않다.

 

하지만 delete를 하지 않게되면 memory leak 발생 가능하고 프로그램이 커지면 커질수록 심해지고 찾기 어렵다.

 

그리고 allocation이 느리다.

출처 : https://youtu.be/x_SA9Ss8x14