Menu
CoddyTech

ムーブ専用の所有権

Coddyの「C開発者のためのC++」コースのレッスン 41/48。

Cでは、所有権の移譲はプログラマーの慣例であり、多くの場合、ポインターをコピーしてから元のポインターをクリアします。C++のunique_ptrは排他的な所有権を表し、コピーを禁止します。unique_ptrをムーブすると所有権が移譲され、元のオブジェクトはクリアされます。その他のムーブ元の標準オブジェクトも一般に有効な状態ですが、値は未規定の場合があります。

C

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdbool.h>

int main(void){
char* a=malloc(4);if(!a)return 1;strcpy(a,"oak");char* b=a;a=NULL;printf("%s %s\n",a?"true":"false",b);free(b);
return 0;
}

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";
}

各プログラムを個別に追跡してください。これらの例では、課題とは異なる操作やデータを使って概念を説明しています。ソースとターゲットの出力が一致するとは限りません。

challenge icon

チャレンジ

簡単

入力: 整数。Boxはunique_ptrを介して整数を所有します。Boxを移動すると所有権が移ります。has_valueは値を所有しているかどうかを返し、getは所有している値、または空の場合はゼロを返します。ドライバーはBoxをムーブコンストラクトし、その後ムーブ代入します。移動元のBoxは空でなければなりません。コピー操作は禁止されています。

編集可能なモジュール: 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";
}
quiz icon腕試し

このレッスンには短いクイズがあります。レッスンを始めて解答し、進捗を記録しましょう。

C開発者のためのC++のすべてのレッスン

自分で練習してみよう: C++オンラインコンパイラ