473,769 Members | 1,743 Online
Bytes | Software Development & Data Engineering Community
+ 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<s td::ofstream> filePtr;
std::_Ios_Openm ode mode;
public:
classA(const std::string& name, bool isAppended = true);
virtual ~ClassA{};
void setAppended(boo l 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(is Appended); // to set
mode
*filePtr = *(new std::ofstream(f ileName.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(f ileName.c_str() )){
this->setAppended(is Appended);
}

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 "setAppende d" returns bool and put
it this way:

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

which looks rather ugly... Putting in the same place the code of
function "setAppende d" 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(fileNam e.c_str(), mode);
fileRef = tempRef;
///

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

regards,
Anton

Oct 4 '05 #1
4 2210
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<s td::ofstream> filePtr;
std::_Ios_Openm ode mode;
public:
classA(const std::string& name, bool isAppended = true);
virtual ~ClassA{};
virtual ~classA{}

void setAppended(boo l 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(is Appended); // to set
mode
*filePtr = *(new std::ofstream(f ileName.c_str() , mode)); //
Compile error
Why are you dereferencing?

Try:
filePtr = new std::ofstream(f ileName.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(f ileName.c_str() )){
You're not dereferencing here.
this->setAppended(is Appended);
}

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 "setAppende d" returns bool and put
it this way:

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

which looks rather ugly... Putting in the same place the code of
function "setAppende d" 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(fileNam e.c_str(), mode);
fileRef = tempRef;
///

..won't work because I cannot define reference for auto_ptr like this:
const std::auto_ptr<s td::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(f ileName.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
285
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 your Visual Studio and compile it + run it; so you can see what the actual problem is. Thanks. code:
1
4626
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, section "Static initialization dependency". There is a example to show how to solve the prolem involved with a technique first poineered by Jerry Schwarz while creating the iostream library (because the definitions for cin, cout, and cerr are static...
5
4272
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 connects to the Server, the server will process and send result to the client.(This is Client Server Application. The Server side Code is implementd in th OnStart method Of Windows Service). When i tried the Client Server Application in Console...
2
1864
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 (an endless loop). i thought that BinaryReader.ReadByte advanced to the next byte? i had it time out after 1000 iterations, and keeps outputting the same byte. any help appreciated, my code is below: Imports System.io
0
1555
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 that serve up a file. So I use vpp to code up an initialization even, virturalfile, virtualdirectory and virtualpath provider. I have a simple file for testing testing.aspx (no codebehind) that just sets a label to 'hello world' on pageload. Now...
1
1639
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 memory to a character pointer to store contents of that file.. i am doing this because the contents of the file may change for each "read" operation. and i will use this poiter(dynamically allocated) for sendto() call. please help.. thnx in advance.
6
2318
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> name = NITROGEN;
1
2974
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 : Defines the entry point for the console application. #include "stdafx.h" #include <stdio.h> #include <conio.h> #include <iostream>
2
1930
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 Report control. My problem is in rendering the report from the rdlc file for printing to a line printer. Following the example from MSDN Help at http://msdn2.microsoft.com/en-us/library/ms252172(VS.80).aspx I can print the rdlc report...
0
9423
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 effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10212
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10047
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
9995
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 Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9863
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
1
7410
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 presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6674
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5304
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 last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5447
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?

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.