Re: mysterious destructors
Paavo Helde <myfirstname@osa.pri.ee> writes:
You can have an example with 2 instances (of class c) and no memory leaks
as well:
#include <iostream>
#include <ostream>
#include <memory>
struct c
{ int v;
c( int const x ): v( x )
{ ::std::cout << "constructor of instance #" << v << ".\n"; }
~c(){ ::std::cout << "destructor of instance #" << v << ".\n"; }
void print(){ ::std::cout << "I am instance #" << v << ".\n"; }};
int main()
{ std::unique_ptr<c> o(new c( 1 ));
o->print();
o = std::unique_ptr<c>(new c( 2 )); /* overwrite */
o->print(); }
Actually, I wanted to observe how C++ interprets an example
someone posted into the C newsgroup recently. Here is my
attempt of a translation into C++:
#include <iostream>
#include <ostream>
#include <memory>
struct c /* this struct is as above (as before) */
{ int v;
c( int const x ): v( x )
{ ::std::cout << "constructor of instance #" << v << ".\n"; }
~c(){ ::std::cout << "destructor of instance #" << v << ".\n"; }
void print(){ ::std::cout << "I am instance #" << v << ".\n"; }};
::std::unique_ptr< c >f( ::std::unique_ptr< c >* p )
{ *p = ::std::make_unique< c >( 2 ); /* <- sequence point! (semicolon) */
return ::std::make_unique< c >( 1 ); }
int main()
{ ::std::unique_ptr< c >o( f( &o )); o->print(); }
Does this program violate any rule of C++?