简体   繁体   中英

Call method only once for EACH object of the class NOT STATIC

I wrote a class where the constructor is private.

I need to assign the given value to the private members ONLY ONCE

in the method construct(int a) .

It should be something like a constructor but not a constructor !

Every time this construct(int a) is called after the first time, I do not need to reassign anything to that specific OBJECT.

How to achieve that without any booleans?

I thought of boost::call_once but it calls construct(int a) once for ENTIRE CLASS! and I need to call this function ONCE for EACH OBJECT .

just like ctor! Any ideas?

UPDATE 1: The Constructor is private. But the class has some members those values can be assigned from the outside but only ONCE

I am trying to achieve some automatisation for checking if a function was called or not already without using bool wasCalled or something like that.

UPDATE 2:

LT::Pointer lut = LT::New();
    std::vector<double> points;
....
    lut->construct(points);

The second time

lut->construct(points);

is called - error should be given, or just somehow make it impossible.

Direct Answer :

You can devise a wrapper that applies "assign-once" semantics to the wrapped object.

However, you can not make the compiler detect that a value is being set for the second time at compile time, so you should be prepared to make it assert/throw at runtime.

Background/look around

As others have said, this smells very much like a design flaw. Why can't you have the New operation forward constructor parameters (a-la make_shared , make_unique ?):

template <typename T, typename... Args>
    SmartPointer<T> genericNew(Args&&... args) {
         return SmartPointer<T>(new T(std::forward<Args>(args)...));
    }

Of course, there could be specialized factory methods that even know how to set private properties after construction. Make the factory methods friends, to preven others from using the hidden property (setters) after creation by the factory:

struct X { 
     int a; 
     X(int i) : a(i) {}

     typedef SmartPointer<X> Ptr;

     static Ptr New(int a, int init_only) {
         Ptr p(new X(a));             
         p->init_only = init_only;
         return p;
     }

   private:
     int init_only;
};

(here I opted to make the New factory method a static member, so it's implicitly a friend)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM