Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to prevent others create a new instance of your class on stack ?

Suppose you write a class A, with constructor being private (to prevent others to create it on stack) then one day another developer add a new ctor, say A(int), and want to use inside main():

A a(1)

to create it on stack. How do you prevent that?

my solution:

Declare a public constructor

  A(void& input )
   {
 Cerr << “please do not create it on stack” << endl ; 
  exit(1);
   }

I am not sure it is correct ?

thanks

like image 847
Jack Avatar asked Nov 29 '22 15:11

Jack


1 Answers

As others say, you can't prevent people who can edit your class from making it do pretty much anything...BUT...

...if you want a slightly more compiler-enforceable method than a comment, you could inherit from a class which has no default constructor. Anyone writing a constructor would be (hopefully) led to take notice of it. You could make its name cue people into taking certain precautions.

Something like this:

class DoNotStackConstruct {
protected:
    DoNotStackConstruct(const char* dummy) {}
};

class A : protected DoNotStackConstruct {
private:
    A () : DoNotStackConstruct ("PLEASE make all A constructors private!") {
       // your code here
    }
public:
    static std::tr1::shared_ptr<A> newA() {
        return std::tr1::shared_ptr<A>(new A);
    }

/* ... a bunch of code ... */
/* ... then someone later adds the following ... */

public:
    A (int i) {
        // can't force them to make it private, but...
        // this won't compile without mentioning DoNotStackConstruct
    }
};

Once you start using C++11 there will be "delegating constructors", and this trick will have a bit less teeth:

Can I call a constructor from another constructor (do constructor chaining) in C++?

Then they'll be able to delegate to A() without visiting the source line and copying the "hey, don't make your constructor public!" text. But by default, they'll still get the compiler error the first time they try.

like image 189
HostileFork says dont trust SE Avatar answered Dec 04 '22 14:12

HostileFork says dont trust SE