이동 전용 소유권
Coddy의 Swift 개발자를 위한 C++ 코스 레슨. 48개 중 41번째.
String 및 Array와 같은 Swift 값은 대입할 때 복사되며, 쓰기 시 복사 방식 덕분에 복사 비용이 저렴하므로 원본을 계속 사용할 수 있습니다. ~Copyable로 표시된 타입은 이동 전용입니다. 대입하면 원본이 소비되고, 컴파일러는 이후의 원본 사용을 거부합니다. C++에서는 std::move와 같은 우값 문맥이 필요합니다. 이는 이동 연산을 가능하게 하는 캐스트이지 그 자체로 이동은 아니며, 이후 원본을 사용하지 못하게 하는 것도 없습니다. C++의 unique_ptr은 이동 전용입니다. 이동하면 소유권이 이전되고 원본은 빈 상태가 됩니다. 이동된 다른 객체는 지정된 값을 가질 필요가 없습니다.
Swift
struct Token: ~Copyable {
let name: String
}
func demo() {
var a = "oak"
let b = a
a += "!"
print(a, b)
let t = Token(name: "pine")
let u = t
print(u.name)
}
demo()
C++
#include <iostream>
#include <string>
#include <vector>
#include <array>
#include <map>
#include <set>
#include <algorithm>
#include <memory>
#include <sstream>
#include <stdexcept>
#include <utility>
int main(){
auto a=std::make_unique<std::string>("oak");auto b=std::move(a);std::cout<<std::boolalpha<<static_cast<bool>(a)<<" "<<*b<<"\n";
}
각 프로그램을 독립적으로 추적하세요. 이 예제들은 과제와 다른 연산이나 데이터를 사용해 개념을 보여 줍니다. 원본 출력과 대상 출력이 같다고 가정하지 마세요.
챌린지
쉬움입력: 정수. Box는 unique_ptr을 통해 정수를 소유합니다. Box를 이동하면 소유권이 이전됩니다. has_value는 값의 소유 여부를 반환하고, get은 소유한 값이나 비어 있는 경우 0을 반환합니다. 드라이버는 이동 생성한 다음 이동 대입합니다. 이동된 객체는 비어 있어야 합니다. 복사 연산은 삭제되어 있습니다.
편집 가능한 모듈: Box.cpp, Box.hpp. 필요한 각 형식에는 고유한 이름의 헤더와 구현 파일이 있습니다. 모든 공개 시그니처를 보존하세요. 잠긴 main.cpp는 표준 입력을 읽고 API를 직접 호출합니다. 명시된 경우 공개 API의 동작도 독립적으로 확인합니다. API 내부에서 출력하지 말고 값을 반환하세요. 정수 입력과 결과는 부호 있는 int 범위에 들어갑니다. 별도로 명시되지 않은 텍스트는 ASCII입니다.
직접 해보기
#include <type_traits>
#include "Box.hpp"
#include <iostream>
int main(){ static_assert(!std::is_copy_constructible<Box>::value,"This owning type must not be copyable");
{Box a(17);Box b(std::move(a));if(a.has_value()||!b.has_value()||b.get()!=17)return 21;Box c(2);c=std::move(b);if(b.has_value()||c.get()!=17)return 22;c=std::move(c);if(!c.has_value()||c.get()!=17)return 23;}
std::vector<std::string> rows; std::string line; while(std::getline(std::cin,line)) rows.push_back(line);
std::istringstream in(rows.empty()?"":rows[0]);int n;in>>n;Box a(n);Box b(std::move(a));Box c(0);c=std::move(b);std::cout<<std::boolalpha<<a.has_value()<<" "<<b.has_value()<<" "<<c.get()<<"\n";
}
이 레슨에는 짧은 퀴즈가 포함되어 있습니다. 레슨을 시작해 문제를 풀고 진행 상황을 기록하세요.
Swift 개발자를 위한 C++의 모든 레슨
직접 연습해 보세요: 온라인 C++ 컴파일러