limit the number of instance of a class - c++

I want to put a limit on the number of instances you can make of a class.
I have the following code:
class A {
static int cnt;
int x;
public:
A() {
cout<<"ctor called\n";
}
void* operator new(size_t size_in) {
if(cnt<=10) {
void *p=malloc(size_in);
if(p==NULL) {
throw bad_alloc();
} else {
cout<<"Memory allocation successful\n";
++cnt;
return p;
}
} else {
throw bad_alloc();
}
}
~A() {
cout<<"Cleaning up the mess\n";
}
};
int A::cnt=0;
int main() {
A *a[20];
for(int i=0;i<20;++i) {
try {
a[i]=new A();
} catch (bad_alloc &e) {
cout<<"Error in allocating memory\n";
}
}
try {
A b;
} catch (bad_alloc &e) {
cout<<"Error in allocating memory on stack\n";
}
return 0;
}
Using a static counter and overloading the new operator I am able to put a limit on the number of objects that can be created on Heap. I want to limit the number of instances created on Stack also. One way is to make constructor private and provide a public API which first checks the counter and then returns accordingly.
Is there any other way of doing this?

Is there any other way of doing this??
You may just increase and check the counter in the constructor, the object will be destroyed if you throw an exception out of it. Furthermore, you won't have to distinguish between stack and heap.

The best way to do it is to create helper template class and count objects using constructor and destructor:
class instance_limit_reached : public std::logic_error
{
public:
using logic_error::logic_error;
};
template<typename T, int MaxInst>
class LimitInstances
{
static std::atomic<int> instanceCount;
void onNewInstance() {
chekcTheLimit();
++instanceCount;
}
void chekcTheLimit() {
if (instanceCount >= MaxInst)
throw instance_limit_reached(std::string("Limit reached for ") + typeid(T).name());
}
public:
~LimitInstances() {
--instanceCount;
}
LimitInstances() {
onNewInstance();
}
LimitInstances(const LimitInstances<T, MaxInst> &) {
onNewInstance();
}
LimitInstances(LimitInstances<T, MaxInst> &&) {
onNewInstance();
}
};
Live example with field use or example with CRTP
Now there is one important question, when object is moved do you consider this as a new instance (my example) or old instance (my code needs tweaking)?

For fun, this is how I would do it: a CRTP design to be reusable with thread safe code:
template<class ToLimit,size_t MaxInstances>
class InstanceLimiter{
static inline std::atomic<int> instances=0;
private:
static increase_count(){
//memory order relaxed is sufficient because there is
//only one modification order for each atomic objects.
int actual=instances.load(std::memory_order_relaxed);
do{
if (actual>=MaxInstances) throw some_error{};
} while (instances.compare_exchange_weak(actual,actual+1,
std::memory_order_relaxed,std::memory_order_relaxed));
}
protected:
//Provide definition for default constructor, copy constructor
// and copy assignment operator so that defaulted derived special
// member function behave as expected.
InstanceLimiter(){increase_count();}
InstanceLimiter(const InstanceLimiter&){increase_count();}
InstanceLimiter& operator=(const InstanceLimiter&){
increase_count();
return *this;
}
~InstanceLimiter(){
instances.fetch_add(-1,std::memory_order_relaxed);
}
};
class A: InstanceLimiter<A,10> {
int x;
public:
A() {
//InstanceLimiter default constructor implicitly called
cout<<"ctor called\n";
}
A(int x)
//InstanceLimiter default constructor implicitly called here
:x{x}{}
//Implicitly declarer move/copy constructor/assignement implicitly calls
// the copy constructor/assignment of InstanceLimiter
~A() {
cout<<"Cleaning up the mess\n";
//Default destructor of InstanceLimiter implicitly called here.
}
};
Last but not least: if you plan to use it in real code, consider to make your class A noexcept default and move constructible by providing it a default state that does not count as an instance.

I want to limit the number of instances created on Stack also
If you want different limits for Heap and Stack object, it seem to me that the cleaner way is the one of the private constructor with friend make functions (one for heap objects and one for stack object) with counters inside the make functions.
I mean... you can write A as follows
class A
{
private:
int x;
A (int x0 = 0)
{ std::cout << "ctor called" << std::endl; }
public:
~A()
{ std::cout << "cleaning up the mess" << std::endl; }
friend A * makeAinHeap (int);
friend A makeAinStack (int);
};
and the make-in-heap function is simply
A * makeAinHeap (int x)
{
constexpr auto maxAH { 3u };
static auto ah { 0u };
if ( ++ah > maxAH )
throw std::runtime_error("no more A in Heap");
return new A{x};
}
and the analogous make-in-stack function is
A makeAinStack (int x)
{
constexpr auto maxAS { 2u };
static auto as { 0u };
if ( ++as > maxAS )
throw std::runtime_error("no more A in Stack");
return A{x};
}
You can check all with the following main()
int main ()
{
auto p1 { makeAinHeap(0) }; // OK
auto p2 { makeAinHeap(0) }; // OK
auto p3 { makeAinHeap(0) }; // OK
//auto p4 { makeAinHeap(0) }; // throw an exception
auto s1 { makeAinStack(0) }; // OK
auto s2 { makeAinStack(0) }; // OK
//auto s3 { makeAinStack(0) }; // throw an exception
delete p1;
delete p2;
delete p3;
}

Related

Returning an object by value which should conceptually not be copied

I'd like to have an object whose constructor acts as a begin() and it's destructor acts as an end(), and provides functions that are only valid between these two calls as methods. However... I also want to use named constructors, and also have functions that act as factories for this object too.
// this is the object I'm returning by value
class DrawCommand {
DrawCommand(CanvasBuffer & guts, uint32 threadID); // private
public:
// begin(); starts a draw command
static DrawCommand inMT(Canvas & canvas); // for main thread
static DrawCommand inWK(const Job & jobRef); // for worker threads
// end(); submits command to rendering thread
~DrawCommand();
// returns false if draw can be ignored (doesn't need to be respected)
operator bool();
// commands which would break if used outside of begin() and end()
void doStuff();
};
// this class has a factory that returns by value
class Canvas{
public:
DrawCommand debugDrawCommandMT(){
DrawCommand cmd;
...
return cmd;
}
};
// usage
{
DrawCommand cmd1 = DrawCommand::inMT(canvas);
cmd1.doStuff();
} // cmd1.~DrawCommand() upon exiting scope
if (DrawCommand cmd2 = canvas.debugDrawCommandMT()) {
cmd2.doStuff();
} // cmd2.~DrawCommand() upon exiting scope
This means returning this object by value.
This is troublesome as RVO is an optional optimization with side effects. When omitted, this prompts calls to the constructor and destructor. These functions are expensive as they access resources guarded by mutex, so I need to avoid that behavior.
What is the easiest way to ensure this object behaves as if RVO is always taking place when returned?
To be specific, what I'm after is the behavior of RVO, I've been able to find information on what it is and how to hint it's usage to the compiler. But I want to get the side-effect of RVO in a reliable way. Conceptually, it should be as if the object returned isn't a copy, but the original, even if that's not reality.
So this is what I had in mind.
You can run this and see the console output.
It's a moveable only type (if you attempt to copy you'll see a compiler error about a deleted function).
It prevents sending the command to the thread if the object has been moved from.
class DrawCommand {
public:
explicit DrawCommand( std::string state ) noexcept
: state_{ std::move( state ) }
, moved_{ false }
{ }
DrawCommand( const DrawCommand& ) = delete;
DrawCommand& operator=( const DrawCommand& ) = delete;
DrawCommand( DrawCommand&& other ) noexcept
: state_{ std::exchange( other.state_, { } ) }
, moved_{ std::exchange( other.moved_, true ) }
{ }
DrawCommand& operator=( DrawCommand&& other ) noexcept {
state_ = std::exchange( other.state_, { } );
moved_ = std::exchange( other.moved_, true );
return *this;
}
~DrawCommand( ) {
if ( moved_ ) std::cout << "Skip sending to thread\n";
else std::cout << "Sending " << state_ << '\n';
}
private:
std::string state_;
bool moved_;
};
static auto create_command( ) -> DrawCommand {
return DrawCommand{ "Some state" };
}
auto main( ) -> int {
{
auto cmd{ create_command( ) };
}
}
This is what I meant, but then in code:
(If needed change to shared_ptr and forget about move constructor and just use copy constructor)
#include <iostream>
#include <memory>
class ClassItf
{
public:
virtual ~ClassItf() = default;
virtual void DoWork() = 0;
protected:
ClassItf(const ClassItf&) = delete;
ClassItf(ClassItf&&) = delete;
ClassItf& operator=(ClassItf&) = delete;
ClassItf() = default;
};
// hide implementation
namespace details
{
class ImplementationClass :
public ClassItf
{
public:
ImplementationClass()
{
std::cout << "ImplementationClass::ImplementationClass" << std::endl;
}
~ImplementationClass()
{
std::cout << "ImplementationClass::~ImplementationClass" << std::endl;
}
virtual void DoWork() override
{
std::cout << "ImplementationClass::DoWork" << std::endl;
}
};
}
class YourClass :
public ClassItf
{
public:
YourClass() :
m_impl{ std::make_unique<details::ImplementationClass>() }
{
}
YourClass(YourClass&& other) :
m_impl{ std::move(other.m_impl) }
{
std::cout << "YourClass::YourClass moved" << std::endl;
}
virtual void DoWork() override
{
m_impl->DoWork();
}
private:
std::unique_ptr<ClassItf> m_impl;
};
YourClass CreateClass()
{
YourClass retval;
return retval;
}
int main()
{
{
auto obj = CreateClass();
obj.DoWork();
}
std::cout << "Done..." << std::endl;
}

Prevent Base class constructor being called on invalid Derived class initializer

Consider the following example where the construction of Derived class takes a pointer on its constructor's initializer list. Of course I want to check if this pointer is valid and throw an exception otherwise.
My attempt prevents the program to crash but Base part is still constructed before I can throw the exception.
Is there a way I can prevent Base class constructor being called in this case ?
#include <stdlib.h>
#include <iostream>
class Base
{
public:
Base(int val) : val_b(val)
{
std::cout << "Base::CTOR" << std::endl;
}
~Base() { }
int val_b;
};
class Derived : public Base
{
public:
Derived(int *, int);
~Derived() { }
int val_d;
void print(void)
{
std::cout << "Base:\t" << val_b << std::endl;
std::cout << "Derived:" << val_d << std::endl;
}
};
Derived::Derived(int *val1, int val2) : Base(val1 ? *val1 : -1), val_d(val2)
{
if (!val1)
{
throw std::invalid_argument("bad pointer");
}
}
int main()
{
int *a = NULL;
int b = 43;
try
{
Derived *d = new Derived(a, b);
d->print();
}
catch (std::exception &e)
{
std::cout << "Exception: " << e.what() << std::endl;
}
return 0;
}
You might call a function/lambda before calling Base constructor:
Derived::Derived(int *val1, int val2) :
Base([&](){
if (!val1) {
throw std::invalid_argument("bad pointer");
}
return *val1;
}()),
val_d(val2)
{
}
Maybe I misunderstand your question, but consider this simplified example:
#include <iostream>
struct Base {
~Base() { std::cout <<"destructor";}
};
struct Foo : Base {
Foo() : Base() {
throw 1;
}
};
int main()
{
try {
Foo f;
} catch(...){}
}
Output is:
destructor
My attempt prevents the program to crash but Base part is still constructed before I can throw the exception.
That isn't a problem. As always with exceptions, stack is unwinded and the Base part of Foo is properly destroyed. I see nothing wrong in your code (in the sense of seriously broken, though design is debatable). If construction fails and you throw an exception in the body of the constructor, cleaning up what already has been constructed is the best you can do.
I don't get why you want it but anyway have you tried failing in Base ctor rather than Derived ctor?
class Base
{
public:
Base(int *val)
{
if (!val)
{
throw std::invalid_argument("bad pointer");
}
val_b = val;
std::cout << "Base::CTOR" << std::endl;
}
~Base() { }
int val_b;
};

C++ User-defined type conversion failure

template<typename T>
class Pack
{
private:
std::function<T()> _Func = nullptr;
public:
Pack()
{
}
Pack(std::function<T()> func)
: _Func(func)
{
}
~Pack()
{
}
operator T()
{
return _Func();
}
};
What I use is operator T, I want to call _Func implicitly but I cannot even do it explicitly. It seems right but actually error C2440 #MSVC. I use it in two ways:
static member of class (succeeded);
member of class (failed)
(I don't know whether it matters or not)
I'm really wondering why it performs in two ways, and more importantly, how I can put it into my class as a non-static member and successfully call the operator T.
Member of the class:
struct test
{
test()
{
p_ = Pack<int>(std::bind(&test::foo, *this));
}
int foo()
{
std::cout << "test::foo" << std::endl;
return 5;
}
Pack<int> p_;
};
int main()
{
test t;
int x = t.p_;
return 0;
}
This works fine on VS 2013 EE.

Pros/Cons of using operator overloading (new/delete) to implement Singleton

I was brushing up my C++ knowledge and I chose implementing singleton to be starting point. Just I didn't want to implement the classic private constructor & static getInstance method way of doing it.
So here is a Rube Goldberg way,
class Singleton : public IDestroy {
static Singleton* iS; // Singleton instance
static int count; // number of undeleted objects
int a;
public:
Singleton(int A = 0) {
if (!iS) {
a = A;
iS = this;
}
count++;
}
void destroy() {delete this;} // way to destroy HeapOnly
int get() {
return a;
}
static void* operator new(std::size_t size);
static void operator delete(void* ptr);
protected:
// Ensuring construction of HeapOnly objects
// If object created on stack, there is no control of new operator
~Singleton() {
count--;
std::cout << "Destroyed, remaining :" << count << std::endl;
}
};
void* Singleton::operator new(std::size_t size)
{
if (iS)
return iS;
else
return ::operator new(size);
}
void Singleton::operator delete(void* ptr)
{
if (!count)
{
::operator delete(ptr);
iS = 0;
std::cout << "Cleared memory" << std::endl;
}
}
Singleton* Singleton::iS = 0;
int Singleton::count = 0;
And to work well with shared_ptr:
class IDestroy
{
public:
virtual void destroy() = 0;
};
class HeapOnlyDestroyer {
public:
void operator()(IDestroy* s) {
s->destroy();
}
};
Now, I can use the same object like:
a = new Singleton(1);
..
a->destroy();
or
shared_ptr<Singleton> s(new Singleton(1), HeapOnlyDestroyer());
I wanted to know if there are any problems in this approach, also its pros/cons over the classic way of using static getInstance method.
Cons:
It is confusing that object is not actually being created with new
Inheritance is possible that will create mess to maintain singleton functionality (could this be turned into a feature?)
First of all, what is the pro of this implementation?
Just I didn't want to implement the classic private constructor[...]
Why not?
Why not following the least surprise rule and using the Meyers Singleton?
e.g:
http://www.devarticles.com/c/a/Cplusplus/C-plus-plus-In-Theory-The-Singleton-Pattern-Part-I/4/
class Log {
public:
static Log& Instance() {
static Log theLog;
return theLog;
}
void Write(char const *logline);
bool SaveTo(char const *filename);
private:
Log(); // ctor is hidden
Log(Log const&); // copy ctor is hidden
Log& operator=(Log const&); // assign op is hidden
static std::list<std::string> m_data;
};
P.S.: Off the records, my first implementation of "singleton" was like this. After explaining the code to a college for half an hour, suddenly he asked: "Is it a singleton what you are trying to achieve?" I had to confess, I had no idea at that time, what a singleton was.

Property like features in C++?

My use is pretty complicated. I have a bunch of objs and they are all passed around by ptr (not reference or value unless its an enum which is byval). At a specific point in time i like to call CheckMembers() which will check if each member has been set or is null. By default i cant make it all null because i wouldnt know if i set it to null or if it is still null bc i havent touch it since the ctor.
To assign a variable i still need the syntax to be the normal var = p; var->member = new Type;. I generate all the classes/members. So my question is how can i implement a property like feature where i can detect if the value has been set or left as the default?
I am thinking maybe i can use C++ with CLR/.NET http://msdn.microsoft.com/en-us/library/z974bes2.aspx but i never used it before and have no idea how well it will work and what might break in my C++ prj (it uses rtti, templates, etc).
Reality (edit): this proved to be tricky, but the following code should handle your requirements. It uses a simple counter in the base class. The counter is incremented once for every property you wish to track, and then decremented once for every property that is set. The checkMembers() function only has to verify that the counter is equal to zero. As a bonus, you could potentially report how many members were not initialized.
#include <iostream>
using namespace std;
class PropertyBase
{
public:
int * counter;
bool is_set;
};
template <typename T>
class Property : public PropertyBase
{
public:
T* ptr;
T* operator=(T* src)
{
ptr = src;
if (!is_set) { (*counter)--; is_set = true; }
return ptr;
}
T* operator->() { return ptr; }
~Property() { delete ptr; }
};
class Base
{
private:
int counter;
protected:
void TrackProperty(PropertyBase& p)
{
p.counter = &counter;
counter++;
}
public:
bool checkMembers() { return (counter == 0); }
};
class OtherObject : public Base { }; // just as an example
class MyObject : public Base
{
public:
Property<OtherObject> x;
Property<OtherObject> y;
MyObject();
};
MyObject::MyObject()
{
TrackProperty(x);
TrackProperty(y);
}
int main(int argc, char * argv[])
{
MyObject * object1 = new MyObject();
MyObject * object2 = new MyObject();
object1->x = new OtherObject();
object1->y = new OtherObject();
cout << object1->checkMembers() << endl; // true
cout << object2->checkMembers() << endl; // false
delete object1;
delete object2;
return 0;
}
There are a number of ways to do this, with varying tradeoffs in terms of space overhead. For example, here's one option:
#include <iostream>
template<typename T, typename OuterClass>
class Property
{
public:
typedef void (OuterClass::*setter)(const T &value);
typedef T &value_type;
typedef const T &const_type;
private:
setter set_;
T &ref_;
OuterClass *parent_;
public:
operator value_type() { return ref_; }
operator const_type() const { return ref_; }
Property<T, OuterClass> &operator=(const T &value)
{
(parent_->*set_)(value);
return *this;
}
Property(T &ref, OuterClass *parent, setter setfunc)
: set_(setfunc), ref_(ref), parent_(parent)
{ }
};
struct demo {
private:
int val_p;
void set_val(const int &newval) {
std::cout << "New value: " << newval << std::endl;
val_p = newval;
}
public:
Property<int, demo> val;
demo()
: val(val_p, this, &demo::set_val)
{ }
};
int main() {
demo d;
d.val = 42;
std::cout << "Value is: " << d.val << std::endl;
return 0;
}
It's possible to get less overhead (this has up to 4 * sizeof(void*) bytes overhead) using template accessors - here's another example:
#include <iostream>
template<typename T, typename ParentType, typename AccessTraits>
class Property
{
private:
ParentType *get_parent()
{
return (ParentType *)((char *)this - AccessTraits::get_offset());
}
public:
operator T &() { return AccessTraits::get(get_parent()); }
operator T() { return AccessTraits::get(get_parent()); }
operator const T &() { return AccessTraits::get(get_parent()); }
Property &operator =(const T &value) {
AccessTraits::set(get_parent(), value);
return *this;
}
};
#define DECL_PROPERTY(ClassName, ValueType, MemberName, TraitsName) \
struct MemberName##__Detail : public TraitsName { \
static ptrdiff_t get_offset() { return offsetof(ClassName, MemberName); }; \
}; \
Property<ValueType, ClassName, MemberName##__Detail> MemberName;
struct demo {
private:
int val_;
struct AccessTraits {
static int get(demo *parent) {
return parent->val_;
}
static void set(demo *parent, int newval) {
std::cout << "New value: " << newval << std::endl;
parent->val_ = newval;
}
};
public:
DECL_PROPERTY(demo, int, val, AccessTraits)
demo()
{ val_ = 0; }
};
int main() {
demo d;
d.val = 42;
std::cout << "Value is: " << (int)d.val << std::endl;
return 0;
}
This only consumes one byte for the property struct itself; however, it relies on unportable offsetof() behavior (you're not technically allowed to use it on non-POD structures). For a more portable approach, you could stash just the this pointer of the parent class in a member variable.
Note that both classes are just barely enough to demonstrate the technique - you'll want to overload operator* and operator->, etc, as well.
Here's my temporary alternative. One that doesn't ask for constructor parameters.
#include <iostream>
#include <cassert>
using namespace std;
template <class T>
class Property
{
bool isSet;
T v;
Property(Property&p) { }
public:
Property() { isSet=0; }
T operator=(T src) { v = src; isSet = 1; return v; }
operator T() const { assert(isSet); return v; }
bool is_set() { return isSet; }
};
class SomeType {};
enum SomeType2 { none, a, b};
class MyObject
{
public:
Property<SomeType*> x;
Property<SomeType2> y;
//This should be generated. //Consider generating ((T)x)->checkMembers() when type is a pointer
bool checkMembers() { return x.is_set() && y.is_set(); }
};
int main(int argc, char * argv[])
{
MyObject* p = new MyObject();
p->x = new SomeType;
cout << p->checkMembers() << endl; // false
p->y = a;
cout << p->checkMembers() << endl; // true
delete p->x;
delete p;
}