Ask Your Question
2

How can a custom copy constructor be utilized to form a std::vector of a class that consists of a std::ofstream?

asked 2023-05-26 01:34:31 +0000

lalupa gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
0

answered 2023-05-26 01:59:01 +0000

djk gravatar image

Here is an example code snippet that demonstrates how a custom copy constructor can be utilized to form a std::vector of a class that consists of a std::ofstream:

#include <iostream>
#include <fstream>
#include <vector>

class MyClass {
public:
    MyClass(const std::string& filename) : file(filename) {}
    // custom copy constructor
    MyClass(const MyClass& other) : file(other.file.rdbuf()->clone()) {}

    void write(const std::string& str) {
        file << str << std::endl;
    }

private:
    std::ofstream file;
};

int main() {
    std::vector<MyClass> v;
    v.emplace_back("file1.txt");
    v.emplace_back("file2.txt");

    v[0].write("This is written to file1");
    v[1].write("This is written to file2");

    return 0;
}

In this example, the MyClass class represents a custom class that has an std::ofstream member variable called file. The custom copy constructor of MyClass uses the std::streambuf::clone() function to clone the underlying stream buffer of the ofstream object in the other object. This ensures that when copying the object, a new ofstream object is created with a new stream buffer, instead of just copying the pointer to the existing stream buffer.

The main function creates a vector of MyClass objects and adds two objects to it, each with a different output file. It then writes a line to each file using the write member function of the MyClass class.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2023-05-26 01:34:31 +0000

Seen: 9 times

Last updated: May 26 '23