Re: Initializing without assigning
Thomas J. Gritzan wrote:
Calle Pettersson schrieb:
#include <fstream>
#include <boost/thread/thread.hpp>
class COMConn {
public:
COMConn(int port);
~COMConn();
char *send(char);
char *send(char, char[]);
private:
void connect(int);
std::ifstream input;
std::ofstream output;
boost::thread inputthread;
boost::thread outputthread;
};
But when I want to initialize the threads and streams, I want to do
something like
void COMConn::connect(int port) {
this->input = std::ifstream("COM1:");
this->inputthread = boost::thread(&input.read); // Not correct, needs
arguments, but skip that for now
//etc for the others
}
Use initialization lists in the constructor if its possible:
void COMConn::connect(int port) : input("COM1:"), inputthread(&input.read)
{
}
This way the constructor of the member objects is called.
As TJG says, you should initialize every member somehow in the
constructor. It looks from your example, however, that you want to
delay creation of several objects until the connect function is called.
To do this, make the members pointers (since you're already using
Boost, use boost::scoped_ptr to get automatic cleanup), initialize them
to 0 in the constructor (scoped_ptr will do this automatically, also),
and then create the objects on-the-fly in your member function:
class COMConn
{
public:
// ...
private:
void connect(int);
std::ifstream input;
boost::scoped_ptr<boost::thread> inputthread;
};
void COMConn::connect( int port )
{
input.open( "COM1:");
inputthread.reset( new boost::thread( /*whatever*/ ) );
}
Cheers! --M