C ++ disable stack instance but allow new delete

I basically want:

class MyClass{
    public:
        MyClass() = default;
    // what should I do?
}

MyClass mc; // compile time error;
auto pmc = new MyClass; //OK
delete pmc; //OK too

I know that I can do this in heaps only by hiding the constructor (now it cannot be outside the class) or hiding the destructor (now it cannot delete outside the class) or hiding both. What if I do not want to introduce any new named function and just want the good old new one to be deleted? Is this possible (even with hacking)?

+4
source share
3 answers

My idea is "like a smart pointer, but not":

#include <iostream>

class MyClass_ {
  private:
    /**/     MyClass_( void ) { }
    /**/    ~MyClass_( void ) { }
  public:
    void     func( void ) const { std::cout << "Hello" << std::endl; }

    friend class MyClass;
} ;

class MyClass {
  public:
    /**/     MyClass( void ) : p( new MyClass_ ) { }
    /**/    ~MyClass( void ) { delete p; }

    // Tricky implementation details follow...
    // The question in all cases is, who owns the MyClass_ that has been
    // allocated on the heap?  Do you always allocate a new one, and then
    // copy the guts?  (That might be expensive!)  Do you change ownership?
    // Then what about the other MyClass?  What does it point to?
    // Or do you share ownership?  Then you need to ref-count so you don't
    // delete too soon.  (And this whole thing turns into an ordinary
    // shared_ptr<MyClass_>)

    /**/     MyClass( const MyClass &o ) { }
    /**/     MyClass( MyClass &&o ) { }
    MyClass &operator=( const MyClass &o ) { }
    MyClass &operator=( MyClass &&o ) { }

    MyClass_ * operator->( void ) { return p; }
    const MyClass_ * operator->( void ) const { return p; }

  private:
    MyClass_ *p;
} ;

int
main( int, char ** )
{
    MyClass  a;                  // this will be destroyed properly
    MyClass *b = new MyClass;    // this will leak if you don't delete it

    a->func( );
    (*b)->func( );

    return 0;
}
+6
source

-, , . , , , ​​ API.

0

private - static ( factory ), .

,

class MyClass{
    private:
        MyClass() = default;
    public:
        static MyClass* make() { return new MyClass;  };
    // what should I do?
}

code:

 auto mc = MyClass::make();

( new MyClass)

... ( MyClass::make) <memory> header.

You can also define your own smart pointer class with their unary operator ->and operator *and your own divergent patterns , inspired by std::make_shared...

just want the good old new and deleted

In genuine C ++ 11, this frowned and might be considered bad style. You should avoid using explicitly newoutside your library and use a smart pointer coding method.

0
source

Source: https://habr.com/ru/post/1687926/


All Articles