Re: auto_ptr not dereferencable
In message <7c6e259510068ca479e2efe3830@news.cn99.com>, raof01
<fera_bill@hotmail.com> writes
Hello mkarja,
On 28 helmi, 07:00, raof01 <fera_b...@hotmail.com> wrote:
Hello mkarja,
"Debug Assertion Failed, auto_ptr not
dereferencable"
please new one instance and is pointed by auto_ptr.
Thank you for the answer, but I'm sorry, I don't understand what you
mean.
Do you mean that I should do something like this:
std::auto_ptr<osCom> m_osCom (new osCom);
I've tried that, but it just gives me an error saying, "error C2059:
syntax error : 'new'"
mkarja
Forgot "()"? :-)
No.
std::auto_ptr<osCom> m_osCom (new osCom());
That won't work either. With or without the () it's the syntax for
defining and initialising a local variable in a function, not the syntax
for defining a class member.
But I think you'd better initialize m_osCom in ctor.
Not "better", _must_. And it's the constructor of _Communicator_ we're
talking about.
BTW, are you coming from C# community or ?
It gives the same syntax error even with
std::auto_ptr<osCom> m_osCom (new osCom());
Do I have to initialize it somehow in the .h or .cpp file before I try
to use it in the .cpp file?
You have to initialize it in the initializer list of Communicator's
constructor(s).
No, I'm not coming from C#. Just never used auto_ptr before and are
bit lost with it, it seems :)
Nothing specifically to do with auto_ptr - you'd have the same issues
with a raw pointer.
Sorry for confusing you. If osCom doesn't have ctor with no arguments,
you should use another ctor of osCom.
The issue is not how to construct osCom, it's how to make Communicator's
constructor initialise its member variable m_osCom.
E.g.
You have:
class osCom
{
public: // All kinds of ctor's but without osCom()
osCom(int) { /* ... */ }
osCom(const string &) { /* ... */ } // ...
};
Then you will use something like below:
std::auto_ptr<osCom> m_osCom (new osCom(0));
or
std::auto_ptr<osCom> m_osCom (new osCom("Hello"));
In the body of a function, that declares a new local variable. In a
class definition it's a syntax error. Either way it doesn't initialise
the member variable.
If you want to initialize it elsewhere, put the initialization into
initialization list of ctor - just a recommendation.
If it's a class member, it's essential.
Communicator::Communicator(/*...*/) : m_osCom(new osCom) { /*...*/ }
You may need to pass additional arguments to osCom's constructor, too.
If for some reason construction of the object has to be delayed, use
auto_ptr's reset() function elsewhere in the code:
m_osCom.reset(new osCom);
All my code can be compiled by g++ 3.4.4.
But it doesn't do what mkarja wants, so how does that help?
--
Richard Herring