Re: Design question related to std::auto_ptr
* Vladimir Jovic:
James Kanze wrote:
On Mar 23, 11:10 am, Vladimir Jovic <vladasp...@gmail.com> wrote:
Alf P. Steinbach wrote:
[...]
Some folks have argued that the same technique must in
practice have to work nicely also for std::auto_ptr, at
least if also Foo::~Foo() is defined in the implementation
file, because how could any compiler manage to screw up
things then? But according to the standard's general rules
it's just UB to do it with std::auto_ptr. And one risks the
compiler warning about that UB, as above.
On my compiler (g++ 4.1.2), modifying the example to this:
//start-snip
#include<memory>
class Details;
class MyConcrete {
private:
std::auto_ptr<Details> details_;
};
int main() {
MyConcrete obj;
return 0;
}
class Details
{};
// end-snip
everything compiles fine (without warning). Am I causing UB in
any way?
Formally, yes. Put the definition of Details in another
translation unit, and g++ complains. It probably doesn't here
due to an artifact of the way it instantiates templates---I
think it parses the complete file before instantiating any
templates. And having seen the complete file, it knows the
structure of Details.
Sorry to be PITA, but I really don't understand this. I changed the
example to this:
// file fr.cpp
#include<memory>
#include "hy1.hpp"
class Details;
class MyConcrete {
private:
std::auto_ptr<Details> details_;
};
int main() {
MyConcrete obj;
return 0;
}
// file hy1.hpp
class Details
{
public:
Details(int a );
~Details();
void inc();
int *b;
};
// file hy1.cpp
#include "hy1.hpp"
Details::Details(int a ) :
b(new int(a))
{
}
Details::~Details()
{
delete(b);
}
void Details::inc()
{
*b += 3;
}
As you can see, Details is in another translation unit, and the compiler
doesn't complain.
What do I have to do to make it complains?
PS Ignore missing guards and style
Not sure whether you can make the compiler complain (there's no guarantee,
that's the general nature of UB).
But above, by virtue of including [hy1.hpp] in the main file [fr.cpp] you have
the definition of Details in both translation units. The definition of a class
is not the collection of member definitions. It is the 'class' thing with
declarations -- and sometimes inline definitions -- of the members, and it
tells the compiler among other things the size of an instance and whether there
is a user defined constructor and/or a user defined destructor.
Remove the #include in [fr.cpp], perhaps the compiler will complain then; anyway
you then have formal UB, even if it's difficult to think of a way the compiler
could realize that and then underhandedly making the program do silly things,
especially considering that you do not instantiate Details.
Cheers & hth.,
- Alf
--
Due to hosting requirements I need visits to <url: http://alfps.izfree.com/>.
No ads, and there is some C++ stuff! :-) Just going there is good. Linking
to it is even better! Thanks in advance!