LearnFrenzy
Sign in Take a free test

Move Semantics · Move Semantics Programs · Question 2

Move-only temporary file wrapper class in C++ Solution, output & explanation

  • Program
  • Medium
  • 0 comments
  • Answer explained
  • Moderated community
Question 2 Back to Exercise

Write a TempFile class that owns a std::FILE* from tmpfile(), is move-only (copies deleted, noexcept moves), closes in its destructor, and can be stored in a vector and returned from functions.

Solution
main.cpp
#include <cstdio>
#include <iostream>
#include <string>
#include <utility>
#include <vector>

class TempFile {
    std::FILE* f_ = nullptr;
    std::string tag_;
public:
    explicit TempFile(std::string tag) : f_(std::tmpfile()), tag_(std::move(tag)) {}
    ~TempFile() { if (f_) { std::fclose(f_); std::cout << "closed " << tag_ << '\n'; } }
    TempFile(const TempFile&) = delete;
    TempFile& operator=(const TempFile&) = delete;
    TempFile(TempFile&& o) noexcept : f_(std::exchange(o.f_, nullptr)), tag_(std::move(o.tag_)) {}
    TempFile& operator=(TempFile&& o) noexcept {
        if (this != &o) {
            if (f_) { std::fclose(f_); std::cout << "closed " << tag_ << '\n'; }
            f_ = std::exchange(o.f_, nullptr);
            tag_ = std::move(o.tag_);
        }
        return *this;
    }
    void write(const char* s) { std::fputs(s, f_); }
    long size() { std::fflush(f_); std::fseek(f_, 0, SEEK_END); return std::ftell(f_); }
};

TempFile make_log(const char* text) {
    TempFile t("log");
    t.write(text);
    return t;
}

int main() {
    std::vector<TempFile> files;
    files.reserve(2);
    files.push_back(make_log("hello"));
    files.emplace_back("cache");
    files[1].write("12345678");
    std::cout << files[0].size() << ' ' << files[1].size() << '\n';
    files[0] = std::move(files[1]);        // closes the old log, takes over cache
    std::cout << files[0].size() << '\n';
    return 0;
}

Output Verified by compiling and running

5 8
closed log
8
closed cache

Exactly one object owns each FILE*. Move assignment closes the handle it already had; moved-from objects hold nullptr and close nothing.

Discussion & Comments 0

Share your method, a shortcut, or ask about a step you didn't follow.

No comments yet. Be the first to share your solution!

Post your comment

Comments appear after a quick review by our team.

Search LearnFrenzy

Esc

Quick links