Question about language compliance

D

DJ Franke

Hi !

The following code compiles on the Borland5 C++ compiler (simplified
version):

class SomeClass{
public:
SomeClass() {
Son = NULL;
}
SomeClass(const SomeClass& sc) {
Son = sc.Son;
}

SomeClass& find() { return *Son; }
SomeClass* Son;
};
SomeClass Useless = Useless.find();

In the case where I encountered it, the find function did do quite some
things and caused a very understandable runtime error, since Useless
was not intialised at that stage.

I looked at the code in the debugger and the standard constructor is
never called; the find function is called first and then the copy
constructor, which means that Useless is known and can be used before
it is initialised.

I am not very good an the language internals, so my question is wether
this is a bug in the compiler, or wether there is a good reason that
this is allowed to happen.

Thanks
 
?

=?iso-8859-1?Q?Ali_=C7ehreli?=

The following code compiles on the Borland5 C++ compiler (simplified
version): [...]
SomeClass Useless = Useless.find();

In the case where I encountered it, the find function did do quite some
things and caused a very understandable runtime error, since Useless
was not intialised at that stage.

Your problem can be expressed in a simpler way:

SomeClass Useless = Useless;

In order to construct Useless, first the right hand side must be evaluated.
Right hand side uses the very object that you are in the process of
constructing. That object is not yet an object; it is not constructed.

The solution: don't do it. :)

Ali
 
D

DJ Franke

Hi !

Thanks for your reply.

I know that I shouldn't do it and why it doesn't do any good, I just
stumbled over it due to a typo and now wonder wether it complies with
the standard (and if then why) or wether the compiler should not allow
it.
 
?

=?iso-8859-1?Q?Ali_=C7ehreli?=

Summary:

Class object = use(object);

DJ Franke said:
I just
stumbled over it due to a typo and now wonder wether it complies with
the standard (and if then why) or wether the compiler should not allow
it.

I stumbled on it a few weeks ago myself.

I think the compiler can give warnings in most (all?) of such cases, because
there is no good of using a non-constructed object to construct the same
object. A quality of implementation issue I guess... :/

Ali
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,020
Latest member
GenesisGai

Latest Threads

Top