C++ Non-destructible classes - c++

Is there any way in C++ to create class within a function, and then prevent it from destructing?
like
class someclass {
public:
int x;
someclass() { x = 0; };
}
someclass::x;
and then somewhere
someclass * somefunction()
{
someclass somecl ();
return &somecl;
}
So we call function 'somefunction' and get pointer to class for later using. I need it to exist as long as program runs/it destructed by other function. Is there any way to do it without storing it inside arrays or vectors?

I'm not sure if what you're looking for is a way to define an object once and only once, returning a pointer to the same object each time, or to create a factory function that returns the a newly constructed object each time. If it's the second, look at previous answers. If it's the first, check out static variables. As an example, you could write
someclass * somefunction()
{
static someclass somecl ();
return &somecl;
}
This ensures that somecl is only defined once, when the function is initially run and that it will be alive until your program exits. (For a more precise description of the order of cleanup for static variables, see here.)

Yes, you have to allocate the memory on the heap and then delete the memory when you are done.
someclass * somefunction()
{
return new someclass();
}
int main()
{
someclass * myclass = somefunction();
// do stuff with myclass
delete myclass;
return 0;
}

someclass * somefunction()
{
return new somecl ();
}
You were very close :)

You could create it on the heap rather than the stack:
someclass * somefunction()
{
return new someclass();
}
You may also want to consider returning it in a smart pointer, to explicitly transfer ownership and control its lifetime.

I'm not exactly sure what you are driving at, I can imagine two different use cases where you would want to make a class indestructible.
Case 1: Singleton
The idiomatic way to do this, is to use a static instance of the class that's declared within an accessor function:
class Foo {
public:
static Foo& globalFoo();
private:
Foo() {};
~Foo() {};
};
Foo& Foo::globalFoo() {
static Foo myFoo;
return myFoo;
}
int main() {
Foo& myFoo = Foo::globalFoo();
}
That way, it is impossible for other code to either construct or destruct any instance of Foo, it can only use the one instance that's provided by the globalFoo() function.
Case 2: Wrapped allocation/deallocation
If you just want to force allocation/deallocation to happen via certain static functions, you only need to make both the constructor and the destructor private (just as in the singleton case), and add static functions to the interface for allocation/deallocation:
class Foo {
public:
static Foo* makeFoo();
static void destroyFoo(Foo* aFoo);
private:
Foo() {};
~Foo() {};
};
Foo* Foo::makeFoo() {
return new Foo();
}
void Foo::destroyFoo(Foo* aFoo) {
delete aFoo;
}
int main() {
Foo* myFoo = Foo::makeFoo();
Foo::destroyFoo(myFoo);
}

Related

How to store pointers to objects that class doesn't own?

I am trying to code two classes FooFactory and Foo. FooFactory initializes an object ToolBox in the constructor and stores it in a unique_ptr as I want that to be cleaned after the factory is destructed. All the instances of Foo should be able to use ToolBox so I am passing ptr to ToolBox object in the constructor of Foo and storing it as bare ptr.
I am new to c++ development so, my questions in the light of general suggestion I heard :
avoid raw pointers when possible
Is the usage of bare ptr to store the tool_box object that Foo doesn't own fine in this case? or Can I do better using smart_ptr?
Is the pattern of passing the ptr to ToolBox from the FooFactory class to every new object the correct or is there something better I can do?
Pseudo-code for my classes:
class FooFactory {
public:
FooFactory() {
tool_box_.reset(new ToolBox());
}
std::unique_ptr<Foo> NewFoo() {
std::unique_ptr<Foo> foo(new Foo(tool_box_.get());
return foo;
}
std::unique_ptr<ToolBox> tool_box_;
}
class Foo {
public:
Foo(ToolBox* tool_box) {
tool_box_ = tool_box;
}
private:
// Not Owned
ToolBox* tool_box;
}
A factory would normally never control the lifetime of an object. It should hand out an appropriate pointer, preferably a std::unique_ptr and the caller determines it's lifetime.
#include <string>
#include <iostream>
#include <memory>
class Box
{
public:
Box() {}
};
class Foo
{
public:
Foo(std::shared_ptr<Box> &box)
: m_box(box)
{
}
virtual ~Foo(){}
void print()
{
std::cout << "Hello World" << std::endl;
}
protected:
Box *getBox()
{
return m_box.get();
}
private:
std::shared_ptr<Box> m_box;
};
class FooFactory
{
public:
FooFactory()
{
m_box = std:make_shared<Box>();
}
std::unique_ptr<Foo> CreateFoo()
{
return std::make_unique<Foo>(m_box);
}
private:
std::shared_ptr<Box> m_box;
};
int main()
{
FooFactory factory;
std::unique_ptr<Foo> foo = factory.CreateFoo();
foo->print();
return 0;
}
One way to store a non-owning "pointer" to an object (while coupling the class with that object) would be to store a reference (or perhaps a const reference) instead of a pointer.
In my experience, the constraint of needing to initialize the class with that reference helps hierarchical design and simplifies lifetime management.

Why create an object with a static shared_ptr returning member?

I've seen such pattern around and am curious what's the benefit of such pattern. What's the difference between creating an object with static and with pure constructor?
class Foo {
static std::shared_ptr<Foo> create(); // why expose this function?
Foo(folly::observer::Observe<Config> config);
};
One reason to do this would be to force all instances of the object to be owned by shared_ptr's (instead of statically constructed). This is especially helpful when using shared_from_this().
For example, consider the following program:
#include <memory>
class Foo;
void globalFunc(const std::shared_ptr<Foo> &) {
// do something with the ptr
}
class Foo
: public std::enable_shared_from_this<Foo>
{
public:
Foo() {}
void classMemberFunc()
{
globalFunc(shared_from_this());
}
};
In this program, a Foo object can access/pass a shared pointer to itself, similar to how it can access/pass the this pointer. When classMemberFunc() is called on an object of Foo, globalFunc receives a reference to a shared_ptr the holds Foo.
However, with this design, Foo needs to be owned by a shared_ptr in the first place.
int main()
{
// valid use
auto sptr = std::make_shared<Foo>();
sptr->classMemberFunc();
}
If a Foo object isn't owned by a shared_ptr, shared_from_this() has undefined behavior before C++17 and a runtime error in C++17.
int main()
{
// invalid use - undefined behavior or runtime error
Foo nonPtrFoo;
nonPtrFoo.classMemberFunc();
}
We would like to prevent this at compile time. We can do this using the static "create" method and a private constructor.
class Foo
: public std::enable_shared_from_this<Foo>
{
public:
static std::shared_ptr<Foo> create() // force shared_ptr use
{
return std::shared_ptr<Foo>(new Foo);
}
void classMemberFunc()
{
globalFunc(shared_from_this());
}
private:
Foo() {} // prevent direct construction
};
int main()
{
// valid use
auto sptr = Foo::create();
sptr->classMemberFunc();
// invalid use - now compile error
Foo nonPtrFoo;
nonPtrFoo.classMemberFunc();
}

Singleton file static vs class private static

Is there any difference or specific advice when it comes to the following approaches for defining singletons?
In 1, the singleton object is a class private static, but in 2, it's a file static.
Note: m_initedObj1 is just there to show that class has state, and use case is to call this singleton->DoSomething() many times, without needing to init this object again.
1)
// header file
class Foo {
private:
static Foo* s_fooSingleton;
Foo();
Obj1 m_initedObj1;
public:
static Foo* Singleton();
static void ClearSingleton();
Bar DoSomething(...);
};
// cpp file
Foo* Foo::s_fooSingleton = nullptr;
Foo::Foo() { m_initedObj1 = InitObj1Somewhere(); }
/*static*/ Foo* Foo::Singleton()
{
if(!Foo::s_fooSingleton)
Foo::s_fooSingleton = new Foo();
return Foo::s_fooSingleton;
}
/*static*/ void Foo::ClearSingleton()
{
if(Foo::s_fooSingleton)
delete Foo::s_fooSingleton;
Foo::s_fooSingleton = nullptr;
}
Bar Foo::DoSomething(...) { // do something }
2)
// header file
class Foo {
private:
Foo();
Obj1 m_initedObj1;
public:
static Foo* Singleton();
static void ClearSingleton();
Bar DoSomething(...);
};
// cpp file
static Foo* s_fooSingleton = nullptr;
Foo::Foo() { m_initedObj1 = InitObj1Somewhere(); }
/*static*/ Foo* Foo::Singleton()
{
if(!s_fooSingleton)
s_fooSingleton = new Foo();
return s_fooSingleton;
}
/*static*/ void Foo::ClearSingleton()
{
if(s_fooSingleton)
delete s_fooSingleton;
s_fooSingleton = nullptr;
}
Bar Foo::DoSomething(...) { // do something }
As JerryGoyal states in the comments, in 2) other methods in the same .cpp file can modify s_fooSingleton.
On the other hand, they are not both thread-safe. If you don't really mind the clearing (calling ClearSingleton() explicitly), just go with the Scott Meyers' version. Otherwise, go with the double checked locking version.
It's really hard to ensure the safety in case of explicitly deleting. You always have to check whether it's deleted before you access it. If it's a multi-threaded executable, checking and using it must be atomic, because it can be deleted just after checking.
Double checked locking could be used to create and delete the singleton, which ensures you that there is only one instance at a time. Yet, it does not ensure the object really exist, since you may accidentally delete it.
You may use smart pointers to count references and delete it if no references exist.
Or even better, see this answer https://stackoverflow.com/a/15733545/1632887.
I just wouldn't delete it explicitly if I were you!
Maybe this will satisfy you more:
class MyClass1 {
private:
MyClass1(){}
public:
MyClass1& Instance() {
static MyClass1 theSingleInstance;
return theSingleInstance;
}
};
class MyClass2 {
private:
MyClass2() {}
public:
MyClass2* Instance() {
static MyClass2* theSingleInstance = new MyClass2;
return theSingleInstance;
}
};
class MyClass3 {
private:
MyClass3() {}
public:
MyClass3* Instance() {
static MyClass3 theSingleInstance;
return &theSingleInstance;
}
};

Disallow/Redirect C++ delete?

I have a module (dll/so) which exports a single factory function which returns an object then called. Using the interface (pure-virtual) users of the module can then create different objects. All object creation is through the interface, and therefore takes place using the run-time associated with my module and not the application run-time.
As the allocation is taking place inside the module, the deletion also needs to be, because if the application has a different run-time to my module, gpf/segfault time. so I have a "release" member, which performs a self-delete.
void foo::release(void)
{
delete this;
}
Everything is working fine, but it does require that the user of the module behaves.
My question is:
Is it possible to stop someone issuing a delete on my object directly (Or redirect it to delete from my modules memory pool)?
If not as a backup plan, is it possible to detect this in my object, so I can throw an assertion to force good behavior?
E.G:
iFoo* foo = createFoo ();
foo->release(); // Allowed and expected
delete foo; // Disallowed
In the comments to the OP, #dave made a suggestion to declare the destructors in your pure interfaces to be protected instead of public. This would outright prevent external code (that is, external to implementation classes) from invoking delete.
For example:
class IFoo
{
protected:
virtual ~IFoo() { }
public:
virtual void release() = 0;
};
class Foo : public IFoo
{
public:
void release() override
{
delete this;
}
};
IFoo* createFoo()
{
return new Foo();
}
int main()
{
auto foo = createFoo();
foo->release(); // Expected
delete foo; // Cannot access protected destructor of IFoo
Return 0;
}
Since your factory functions only expose the pure interfaces, this approach doesn't break down if an implementation class happens to provide a public destructor. If Foo declared a public destructor, a compiler error would still occur in main because main doesn't know that it's actually dealing with a Foo.
On Edit: This approach only makes it more difficult for users to delete the resource - it doesn't outright prevent it. (I'll refrain from deleting this answer, since it might still be useful.)
If you really want keep someone from invoking delete on your objects, make it illegal for them to do so - return a value type from your factory function.
The value type could be a thin wrapper around the actual object and could provide pointer semantics, a la smart pointers.
A rough example:
class IFoo
{
public:
virtual ~IFoo() { }
virtual void release() = 0;
};
class Foo : public IFoo
{
public:
Foo() { }
void release() override
{
delete this;
}
};
// Value type with pointer semantics
template <class T>
class Undeletable
{
private:
T* m_resource;
public:
Undeletable(T* resource)
: m_resource(resource)
{
}
T* operator->()
{
return m_resource;
}
};
// Old factory function
IFoo* createFoo()
{
return new Foo();
}
// New factory function
Undeletable<IFoo> createSafeFoo()
{
return Undeletable<IFoo>(createFoo());
}
int main()
{
auto foo = createFoo();
foo->release(); // Expected
delete foo; // Possible but DO NOT WANT
auto safeFoo = createSafeFoo();
safeFoo->release(); // Expected
delete safeFoo; // Compiler says NOPE
return 0;
}
Unfortunately, this only obfuscates the fact that the user can still delete the resource. For example:
delete safeFoo.operator->(); // Deletes the resource

How to pass a linc to class function and call it?

So I have a class like
class mySafeData
{
public:
void Set( int i )
{
myMutex.lock();
myData = i;
myMutex.unlock();
}
void Get( int& i)
{
myMutex.lock();
i = myData;
myMutex.unlock();
}
private:
int myData;
boost::mutex myMutex;
};
its instance is running. Lets call instance A. I want to create a new class that would take as a start up argument some kind of link to Getter from A and would be capable to somehow save link to thet getter for calling it inside its private methods vhen needed. how to do such thing?
Sounds like you want something like this:
class myOtherData
{
public:
myOtherData(mySafeData& dataSource) :
myDataSource(&dataSource)
{}
private:
// note that if you take the advice in the comments,
// you don't need this wrapper function at all,
// it's simple just to call myDataSource.Get()
int GetData()
{
int result;
myDataSource.Get(result);
return result;
}
mySafeData* myDataSource;
};
mySafeData a;
myOtherData b(a);
// b uses a as its data source (make sure it lives as long!)
I'm not sure what you mean by linc/link. Are you asking for anything more than this pattern?
class Foo {
public:
Foo(mySafeData& d) : data(d) {}
int someFunction() {
int i;
data.get(i);
return i;
}
private:
mySafeData& data;
};
...
Foo f(a);
What's wrong with pointers? Smart, Shared, Scoped... I'll use standard pointers for now.
class B
{
public:
B(mySafeData* ptr) // constructor takes a memory pointer as parameter
:SafeData_ptr(ptr)
{
SafeData_ptr->foo(); // call public function from class A
}
~B() // destructor
{
}
private:
mySafeData* SafeData_ptr; // will hold the mem address of instance A when
// this class is initialized
};
Later on your code, when you have instance A ready, you would do something like this:
B b_demo(&A); // &A passes the memory address of the instantiated object
// and A::foo() will be automatically called when B is constructed.
This is probably not the smartest way to do it, but I think it illustrates the idea.