cpp_auto - 8BitsCoding/RobotMentor GitHub Wiki
- ์๋ฃํ์ ์ถ๋ก
- ๋ค๋ฅธ ์ธ์ด์ auto์๋ฃํ์ ์คํ ์ค ์๋ฃํ์ด ๊ฒฐ์
- ์ค์ ์๋ฃํ์ ์ปดํ์ผํ๋ ๋์ ๊ฒฐ์
- ๋ฐ๋์ auto ๋ณ์๋ฅผ ์ด๊ธฐํํด์ผํ๋ค.
auto x; // Error
auto x = "Chris"; // Ok
- auto๋ฅผ ์ฌ์ฉํ์ฌ ํฌ์ธํฐ์ ์ฐธ์กฐ๋ฅผ ๋ฐ์ ์ ์๋ค.
- ํฌ์ธํฐ๋ฅผ ๋ฐ์ ๋ auto ๋๋ auto* (ํฌ์ธํฐ๋ ์์์ ์ถ๋ก ์ ํด์ค๋ค.)
- ์ฐธ์กฐ๋ฅผ ๋ฐ์ ๋ auto& (์ฐธ์กฐํ์ ๋ฐ๋์ ์ฐธ์กฐํ์ผ๋ก ๋ฐ์์ผํ๋ค.)
// Example
Cat* myCat = new Cat("coco", 2);
auto myCatPtr = myCat; // ๊ฐ๋ฅ? -> Ok! ๊ฐ๋ฅํ๋ค
- ์ปดํ์ผ๋ฌ๊ฐ ์ด๋ ํ์ธ์ง ์์๋ผ ์ ์๋ค.
- ๊ฐ๋
์ฑ์ด ์ข์ง ๋ชปํจ
auto name = object.GetName(); // ํฌ์ธํฐ์ธ๊ฐ?
- ํฌ์ธํฐํ์ ๋ฐ์ ๋๋ auto* ๋ฅผ ์จ์ฃผ๋๋ก ํ์
Cat myCat("CoCo", 2);
Cat& myCatRef = myCat;
auto anotherMyCatRef = myCatRef; // ๊ฐ๋ฅ? -> ๋ถ๊ฐ๋ฅ... ์ฐธ์กฐ๋ ์ฐธ์กฐ๋ก ๋ฐ์
- auto๋ก ์ฐธ์กฐ๋ ๋ฐ์ ์ ์๋ค๋ฉด ๋ฐ๋๊ฒ ์ฐธ์กฐ์ธ์ง ์๋์ง ์ปดํ์ผ๋ฌ๊ฐ ์ด๋ ํฅ ๊ตฌ๋ถํด??
auto a = b; // ์ฐธ์กฐํ๋๋ง์ด์ผ ๋ณต์ฌํ๋๋ง์ด์ผ?
- ๊ทธ๋์ ๋น์ฐํ &๋ฅผ ๋ถ์ฌ์ผํ๋ค.
const int b = 1;
auto& a = b; // const๋ฅผ ์ ์งํ์ฑ ๋ฐ๋ ๊ฒ์ด ๊ฐ๋ฅ? -> ๊ฐ๋ฅ
์ด๊ฑด ์ข์ ์๊ฐ์ผ๊น?
auto& name = object.GetName();
์๋ const๊ฒ ์๋๊ฒ??
์ญ์ ์ข์ง ๋ชปํ๋ค.
const auto& name = object.GetName();
์์ ๊ฐ์ด ์ ํํ๊ฒ const๋ฅผ ๋ช ์ํด์ฃผ์.
- auto ํค์๋๋ ํจ์๊ฐ ๋ฐํํ๋ ๊ฑธ ์ ์ฅํ๋ ๋ฐ ๋๋ก ์ ์ฉ
- ํจ์ ๋ฐํํ์ด ๋ณํด๋ auto๋ ๊ทธ๋๋ก
- ํ๋ ์ด๋ฐ ์ผ์ด ์์ฃผ ๋ฐ์ํ ๊น??
// auto๋ก ๋ฆฌํด์ ๋ฐ๊ธฐ์ ๋ชจ๋ ๊ฐ๋ฅ
// double Add(double a, double b) {
float Add(float a, float b) {
return a + b;
}
int main() {
auto result = Add(10.0, 30.0);
retern 0;
}
- auto ํค์๋๊ฐ ํ์ดํ์ ์ข ์ค์ฌ์ฃผ๊ธดํ๋ค.
- ํ์ง๋ง ๊ฐ๋ ์ฑ์ด ๋จ์ด์ง๋ ๊ฒ์ ์ฌ์ค...
- auto๋ณด๋ค๋ ์ค์ ์๋ฃํ์ ์ ํธํ๋๊ฒ์ด ์ฌ์ค์ด๊ธดํ๋ค.
- ๋จ, ์๋์ ๋ช๊ฐ์ง ์ํฉ์ ์ ์ธํ๊ณค?
- ๋ฐ๋ณต์์๋ autoํค์๋๊ฐ ๋งค์ฐ ์ ์ฉ
// ํ๋ฏธ ์ค์ด ์์ด๋ฆฌ ๊ธธ์ด...
for(std::vector<int>::const_itherator it = v.begin(); it != v.end(); ++it)
{
// do
}
for(auto it = v.begin(); it != v.end(); ++it)
{
// do
}
MyArray<int>* a = new MyArray<int>(10);
// ์๋๊ฑธ ๋ ์ ๊ณ ์ถ์ง๋ ์์
auto* a = new MyArray<int>(10);
- auto๋ณด๋ค ์ค์ ์๋ฃํ์ ๊ถ์ฅ
- auto๋ณด๋ค๋ auto* ๋ก ํฌ์ธํฐ ๋ช ์
- const์ผ ๊ฒฝ์ฐ const๋ฅผ ๊ผญ ์ ์ด์ค๋ค.