Menu
CoddyTech

Move-only Ownership

Lesson 41 of 48 in Coddy's C++ for Python Developers course.

Python assignment neither moves nor clears an owning source. C++ move-only types prevent copying to express exclusive ownership. C++ unique_ptr is move-only. Moving transfers ownership and leaves that source empty; other moved-from objects need not have a specified value.

Python

a = ["oak"]
b = a
a = None
print(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";
}

Trace each program independently. These examples demonstrate the concept with different operations or data from the task; source and target output are not assumed to match.

challenge icon

Challenge

Easy

Input: integer. Box owns an integer via unique_ptr. Moving a Box transfers ownership; has_value returns whether it owns a value, get returns owned value or zero if empty. Driver move-constructs and then move-assigns; moved-from boxes must be empty. Copy operations are deleted.

Editable modules: Box.cpp, Box.hpp. Each required type has its own named header and implementation. Preserve all public signatures. The locked main.cpp reads stdin and calls the API directly. It also checks public API behavior independently where stated. Return values rather than printing inside the API. Integer inputs and results fit signed int; text is ASCII unless stated otherwise.

Try it yourself

#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 iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in C++ for Python Developers

Practice on your own: Online C++ compiler