473,473 Members | 1,733 Online
Bytes | Software Development & Data Engineering Community
Create Post

Home Posts Topics Members FAQ

Problem with initialization of poiter to the file stream

Hi everybody!

I have a small problem regarding the initialization of pointer to the
file stream under some conditions.
Imagine a class which has a pointer to output file stream and some
additinional methods to deal with it, i.e. open/close/write:

classA {
private:
const std::auto_ptr<std::ofstream> filePtr;
std::_Ios_Openmode mode;
public:
classA(const std::string& name, bool isAppended = true);
virtual ~ClassA{};
void setAppended(bool isAppended);
bool isAppended();
bool reopen();
void close();
}

The usage of std::ofstream in my case is well suited to be defined as
auto_ptr.
There is also a variable "mode" which defines in which mode file should
be opened (i.e. appended, truncated etc)

Now I'm trying to write a constructor to set both private variables.
Clearly I would like to open "filePtr" with the mode given by
"isAppended" formal variable.

classA::ClassA(const std::string& fileName, bool isAppended) {
this->setAppended(isAppended); // to set
mode
*filePtr = *(new std::ofstream(fileName.c_str(), mode)); //
Compile error
}

which leads to a compilation error that std::ios_base::operator= is
private.

I could set filePtr in initialization list like this:

ClassA::ClassA(const std::string& fileName, bool isAppended):
filePtr(new std::ofstream(fileName.c_str())){
this->setAppended(isAppended);
}

but then at the moment of "filePtr" initialization its "mode" is not
known yet, meaning that "filePtr" should be reopened again later with
the right "mode".

Putting initialization of "mode" in a list before "filePtr" doesn't
guarantied that it will be initialized before.

There is a solution to make function "setAppended" returns bool and put
it this way:

ClassA::ClassA(const std::string& fileName, bool isAppended):
filePtr(new std::ofstream(fileName.c_str(),
this->setAppended(isAppended))){
}

which looks rather ugly... Putting in the same place the code of
function "setAppended" instead of calling it, duplicates the code.

So all in all I'm wondering whether "filePtr" could be initialized
somehow but in the constructor body and not its initialization list.

the case with using reference like this...

///
std::ofstream& fileRef;
....
std::ofstream tempRef(fileName.c_str(), mode);
fileRef = tempRef;
///

...won't work because I cannot define reference for auto_ptr like this:
const std::auto_ptr<std::ofstream&> filePtr
Any tips will be appreciated!

regards,
Anton

Oct 4 '05 #1
4 2184
Anton Pervukhin wrote:
Hi everybody!

I have a small problem regarding the initialization of pointer to the
file stream under some conditions.
Imagine a class which has a pointer to output file stream and some
additinional methods to deal with it, i.e. open/close/write:
#include <memory>
#include <string>
#include <ostream>
#include <fstream>
classA {
class classA
private:
const std::auto_ptr<std::ofstream> filePtr;
std::_Ios_Openmode mode;
public:
classA(const std::string& name, bool isAppended = true);
virtual ~ClassA{};
virtual ~classA{}

void setAppended(bool isAppended);
bool isAppended();
bool reopen();
void close();
}
;
The usage of std::ofstream in my case is well suited to be defined as
auto_ptr.
Your class doesn't correctly handle copying, which would be disaterous with
an auto_ptr as member.
There is also a variable "mode" which defines in which mode file should
be opened (i.e. appended, truncated etc)

Now I'm trying to write a constructor to set both private variables.
Clearly I would like to open "filePtr" with the mode given by
"isAppended" formal variable.

classA::ClassA(const std::string& fileName, bool isAppended) {
this->setAppended(isAppended); // to set
mode
*filePtr = *(new std::ofstream(fileName.c_str(), mode)); //
Compile error
Why are you dereferencing?

Try:
filePtr = new std::ofstream(fileName.c_str(), mode);
}

which leads to a compilation error that std::ios_base::operator= is
private.

I could set filePtr in initialization list like this:

ClassA::ClassA(const std::string& fileName, bool isAppended):
filePtr(new std::ofstream(fileName.c_str())){
You're not dereferencing here.
this->setAppended(isAppended);
}

but then at the moment of "filePtr" initialization its "mode" is not
known yet, meaning that "filePtr" should be reopened again later with
the right "mode".

Putting initialization of "mode" in a list before "filePtr" doesn't
guarantied that it will be initialized before.
It's guaranteed that it won't. That's because you declared "mode" after
"filePtr". Members are always initialized in the order they are declared
in.
There is a solution to make function "setAppended" returns bool and put
it this way:

ClassA::ClassA(const std::string& fileName, bool isAppended):
filePtr(new std::ofstream(fileName.c_str(),
this->setAppended(isAppended))){
}

which looks rather ugly... Putting in the same place the code of
function "setAppended" instead of calling it, duplicates the code.

So all in all I'm wondering whether "filePtr" could be initialized
somehow but in the constructor body and not its initialization list.
Initializations can only be done in the initializer list.
the case with using reference like this...

///
std::ofstream& fileRef;
...
std::ofstream tempRef(fileName.c_str(), mode);
fileRef = tempRef;
///

..won't work because I cannot define reference for auto_ptr like this:
const std::auto_ptr<std::ofstream&> filePtr


I'm wondering why you don't just add an _instance_ of std::ofstream as a
member.

Oct 4 '05 #2
> Your class doesn't correctly handle copying, which would be disaterous with
an auto_ptr as member.
why it should be disasterous with an auto_ptr as member?
If I disable copy constructor and assignment operator, will it be still
dangerous to use auto_ptr?
Why are you dereferencing?

Try:
filePtr = new std::ofstream(fileName.c_str(), mode);
In case with filePtr definition as auto_ptr this statement won't
compile.
I'm wondering why you don't just add an _instance_ of std::ofstream as a
member.


Good question ;-) I just decided to give a try to use auto_ptr, since
the class is not going to be copied or assigned.

Oct 4 '05 #3
Anton Pervukhin wrote:
Your class doesn't correctly handle copying, which would be disaterous with
an auto_ptr as member.
why it should be disasterous with an auto_ptr as member?


because it has a wrong copy semantics. For the same reason auto_ptr
cannot be used in a container.
If I disable copy constructor and assignment operator, will it be still
dangerous to use auto_ptr?
Then you are fine. But you didn't :-)

I'm wondering why you don't just add an _instance_ of std::ofstream as a
member.


Good question ;-) I just decided to give a try to use auto_ptr, since
the class is not going to be copied or assigned.


Thats not a good reason. Your first question should be: Do I need to allocate
dynamically or not. Only then, after you decided that you need dynamic allocation
you can ask the question if some smart pointer is the way to go.
But in your case, I really see no reason why the stream object has to be allocated
with new. Especially because you say you don't want to copy or assign such an object.
Whats wrong with using an ordinary ofstream member and open the file with open()?

--
Karl Heinz Buchegger
kb******@gascad.at
Oct 4 '05 #4
> Thats not a good reason. Your first question should be: Do I need to allocate
dynamically or not. Only then, after you decided that you need dynamic allocation
you can ask the question if some smart pointer is the way to go.
But in your case, I really see no reason why the stream object has to be allocated
with new. Especially because you say you don't want to copy or assign such an object.
Whats wrong with using an ordinary ofstream member and open the file with open()?


I see your point and need to reconsider mine :-) Thanks for
explanation.

Oct 4 '05 #5

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

0
by: crawlerxp | last post by:
This is the problem: I do not get the output I need when encoding and decoding data using rijndael alghoritm. Look at the code and see what the problem is actually: Please paste this code into...
1
by: Qin Chen | last post by:
I will present very long code, hope someone will read it all, and teach me something like tom_usenet. This question comes to me when i read <<Think in C++>> 2nd, chapter 10 , name control,...
5
by: vinoth | last post by:
Hi, I have created WindowsService Project.In that Project OnStart Method i have written the following Code. In this code the Server is waiting for the connection from client. When the Client...
2
by: Mad Scientist Jr | last post by:
i'm trying to read a file byte by byte (and later alter the data and write it to a 2nd file byte by byte) and running into a problem where it seems to keep reading the same byte over and over again...
0
by: Kenny | last post by:
Help...wimper.. been trying to get a virtualpathprovider to work and I have to be missing something. I want users to be able to enter something like mydomain.com/userentereddirectory/ and have...
1
by: manoharyes | last post by:
hi experts, i am getting a segmentation fault error in this piece of code.. node.c has some contents. my intension is to read the contents of a file into an array then.. dynamically allocate...
6
by: giulianodammando | last post by:
In the development of a simple numerical simulation software i need to read some initialization parameters from a file that looks like: # Global Setup species = 1; \begin{specie}<1>...
1
by: Smita Prathyusha | last post by:
I am facing a problem in writing to COM1. I am using a Win 32 Console mode Program in VC++ the following is the code: If anyone can help me out it will be of great help : // SC_Using_Classes.cpp...
2
by: =?Utf-8?B?UmljaA==?= | last post by:
On my development machine where I have Visual Studio 2005 loaded, I have an app that uses the Report control. I can view data in report format with the Report control -- the data renders OK in the...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
1
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...
1
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new...
0
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The...
0
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
0
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated ...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.