Menu
CoddyTech

移動のみの所有権

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

Goの代入では、移動専用の所有権は提供されません。C++のunique_ptrは単一の所有者を表し、ムーブ操作によって所有権を移します。C++のunique_ptrはムーブ専用です。ムーブすると所有権が移り、移動元は空になります。その他のムーブ後のオブジェクトは、値が指定されている必要はありません。

Go

package main
import ("fmt")

func main(){
a:=[]string{"oak"};b:=a;a=nil;fmt.Println(b[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は所有する値、または空の場合は0を返します。ドライバーはムーブ構築してからムーブ代入します。ムーブ元の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腕試し

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

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

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