목차
LHS and RHS
- LHS : left-hand-side expression
- RHS : right-hand-side expression
ex)
x = 10
LHS : x
RHS : 10
Basics in C++ memeory model
* Each variable has an address
- &x (only in RHS) : return the address of the variable x
- x (in RHS) : return the value assigned to the address of the variable
- x (in LHS) : store the RHS value to the address of the variable
Pointers : a value points to an address
- *x (in RHS) : return the value assigned to the address pointed by the value of the variable x
- *x (in LHS) : store the RHS value to the address pointed by the value of the variable x
Basics of Const keyword : Freeze a memory location to make the location immutable
int main() {
const int x = 16;
int y = 99;
x = 20; // Not allowed since the location pointed by the address of x is immutable
y = 31; // OK
return 1;
}
-> 이 코드를 컴파일 하려고 하면 컴파일에러가 남. (실행에러는 아님)
Const with pointers : mutable pointers cannot point to immutable locations
int main() {
const int x = 16;
int* y = &x; // Not allowed since x is const
*y = 10;
return 1;
}
-> 3번째 줄에서 컴파일에러
int* 형 변수에 const int를 넣을 수 없음. 그렇게 되면 4번째 줄 같은 값변경이 가능해지니까
int main() {
const int x = 16;
const int* y = &x;
*y = 10; // Not allowed since *y is immutable
return 1;
}
-> 4번째 줄에서 컴파일에러
const형 변수의 주소는 const형 포인터에만 넣을 수 있음.
y는 const 포인터니까 y가 가리키는 주소의 값 변경 불가
int main() {
int x = 16;
const int* y = &x;
x = 20;
*y = 10; // Not allowed since *y is immutable
return 1;
}
-> 5번째 줄에서 컴파일 에러
x 값을 바꾸는건 가능하지만, y로 접근하는건 불가능
*이런게 시험문제 나온대*
int main() {
int x = 16;
int z = 30;
int* const y = &x;
y = &z; // Not allowed since y is immutable
return 1;
}
int main() {
int x = 16;
int* const y = &x;
x = 20;
*y = 10; // OK since y is immutable but *y is mutable
return 1;
}
Const with class
Member function can be declared with multiple const keywords
- const at return type: the return value is immutable
- const at parameter type: the argument value is immutable
- const at the end of the function signature: an object pointed by this is immutable
class Car {
public :
Car(std::string name) : name_(name) {}
const std::string* name() { return name_; }
void set_name(const std::string name) { name = name + "hi"; }
void DoSomething() const { name_ = name_ + "hi"; }
private :
std::string name_;
Door doors_[4];
};
int main() {
Car car1("mycar");
std::string* car_name = car1.name();
return 1;
}
Shallow copy vs Deep copy
- Shallow copy copies an address of data
- Deep copy copies data completely