Disallow/Redirect C++ delete? - c++

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

Related

How to pass an abstract class as function parameter, which will then be used after the original goes out of scope?

I have the following abstract class
struct Interface {
virtual ~Interface() = default;
virtual void Do() = 0;
};
And I have one or more concrete class which implements Interface
struct ImplA final: Interface{
virtual void Do() override {printf("DO IN ImplA\n");}
};
struct ImplB final: Interface{
virtual void Do() override {printf("DO IN ImplB\n");}
};
Here is my main code (it is just abstracted away)
int main() {
{
ImplA implA{};
Method(implA);
ImplB implB{};
Method(implB);
// Goes out of scope
}
// some other stuff here
return 0;
}
Here is what Method looks like
I used a global container to show that it lives outside of the scope of the Method as well. They will be used at a later time
std::vector<std::unique_ptr<Container>> containers;
void Method(Interface& myInterfaceReference) {
// to show that it lives out of scope of this method
// how should the reference be passed to Container class
// such that it can be used even after original instances are out of scope
containers.emplace_back(new Container());
}
Finally what container class looks like. ←This is the part I am having difficulty with and open to all ideas as to how to design it.
struct Container {
// I dont mind if it is newly created
Interface& referenceToInterface;
// What to do with the ctor, how to pass it
Container(???) {}
void UseInterface() {
//Do Stuff with referenceToInterface
}
};
Store a smart pointer within Container so that it controls the lifetime of the referred object:
struct Container {
std::unique_ptr<Interface> pointerToInterface;
// What to do with the ctor, how to pass it
Pass a smart pointer:
Container(std::unique_ptr<Interface> i)
: pointerToInterface(std::move(i)) {}
How to pass an abstract class as function parameter, which will then be used after the original goes out of scope?
Pass a smart pointer:
std::vector<Container> containers;
void Method(std::unique_ptr<Interface> i) {
containers.emplace_back(std::move(i));
Method(std::make_unique<ImplA>());
Method(std::make_unique<ImplB>());

How to initialize member variable with super class type depending on constructor argument?

After searching for hours, I end up here. I have a Container class with a pointer to Base class as member variable. This should either refer to Spec1 or another inherited classes of Base, which I omitted here. The type should be determined by the argument in constructor (e.g. string, enum, int, etc.).
I read much about dynamic memory allocation and why it should be avoided whenever possible. Is it possible to avoid here? Isnt any usual object destroyed after the constructor? Or is the design idea completely wrong? I come from Java :( Thanks in advance.
class Base{
public:
virtual ~Base(){}; // required?
virtual void doSomething() = 0;
};
class Spec1 : public Base {
public:
Spec1(){};
Spec1(int i){
// whatever
}
void doSomething(){
std::printf("hello world");
}
};
class Container{
public:
Container(String type_message){
if (type_message.compare("We need Spec1")){
m_type = new Spec1(1);
} // add more ifs for other types (Spec2, Spec3 etc.)
}
void doSomethingWithSpec(){
m_type->doSomething();
}
private:
Base* m_type;
};
int main (int argc, char **argv){
Container a ("We need Spec1");
a.doSomething();
}
Requiring Container to be aware of every possible derived class of Base does not sound like good design. That is what factory functions are for.
Have Container store that object as std::unique_ptr to avoid memory leaks and manual memory management.
struct Base {
virtual ~Base() = default;
virtual void doSomething() = 0;
};
struct Spec1 : Base {
void doSomething() override {
std::printf("%s\n", __PRETTY_FUNCTION__);
}
};
// Factory function.
std::unique_ptr<Base> createBase(std::string const& type) {
if(type == "Spec1")
return std::unique_ptr<Base>(new Spec1);
throw std::runtime_error("Unknown type " + type);
}
class Container {
std::unique_ptr<Base> m_type;
public:
Container(std::string const& type)
: m_type(createBase(type))
{}
void doSomething(){
m_type->doSomething();
}
};
int main() {
Container a ("Spec1");
a.doSomething();
}
Constructor works like any other function. Local variables are allocated in stack and get out of scope whenever the function completes whereas dynamic memory allocation is done in stack and needs to be explicitaly deallocated (in C++ and not in Java) before the function completes.
However in your case
m_type = new Spec1(1);
new Spec1(1) is dynamically allocated in heap and won't get destroyed on completion of Constructor code. The reference is stored in the member variable of the class. So as long as the instance of class Container is in scope, the memory allocated to Spec1(1) can be referred.
To compare just consider other scenario.
Container(String type_message){
Base* m_type;
if (type_message.compare("We need Spec1")){
m_type = new Spec1(1);
} // add more ifs for other types (Spec2, Spec3 etc.)
}
Here as soon as constructor finishes, m_type will go out of scope but new Spec1(1) will still be there in heap as the memory leak.

How to create a spy class against the clone idiom in C++

Coming from the Java/PHP world, I am still new to C++. Some simple things to do in other languages are a bit trickier to do in C++.
My main issue is the following. Right now, I have a class (ie. "Something") for which the constructor is injected with a virtual class dependency (ie. a children of "Base"). Then, the constructor stores this injected instance in a unique_ptr<Base> class field (using the clone idiom). This works well at the application level, everything seems to works as expected. Here is the sample code:
class Base {
public:
virtual std::unique_ptr<Base> clone() = 0;
virtual void sayHello() const = 0;
};
class Something {
public:
explicit Something(Base &base) { this->base = base.clone(); }
void sayHello() const { base->sayHello(); }
private:
std::unique_ptr<Base> base;
};
But to make sure it does, I wrote unit tests to test its behavior. In those tests, I want to assert the injected dependencies methods are actually called. So logically, injecting a "spy" dependency should do the trick.
Here is what I did at first:
class SpyDerived : public Base {
public:
explicit SpyDerived() = default;
SpyDerived(const SpyDerived &original) { this->someState = original.someState; }
std::unique_ptr<Base> clone() override { return std::make_unique<SpyDerived>(*this); }
void sayHello() const override { std::cout << "My state: " << someState << std::endl; }
void setSomeState(bool value) { this->someState = value; }
private:
bool someState = false;
};
This is the main function I use to this this out:
int main() {
SpyDerived derived;
Something something(derived);
derived.setSomeState(true);
something.sayHello();
}
For obvious reasons, someState value on print is always false. I get that the Derived instances in Something is a new copy of Derived and no longer the one that was created in the main function.
So basically, what I am trying to achieve here is to have the Something class always use the SpyDerived instance created in the main function. Is there any way I could make this work. I am trying to avoid changing the design just for test purposes.
I am using MSVC 2015 to compile the code. Keep in mind that smart pointers, C++ idioms, copy/move constructors are fairly new concepts for me.
Thanks for your help.
Well, do you want to clone your instance, or simply reference that instance?
The clone idiom is made to copy the instance of a class, making the new instance independent of the old instance.
You are basically making this, in term of PHP:
<?php
interface Base {
public function sayHello();
}
class SpyDerived implements Base {
private $someState = false;
public function sayHello() {
echo 'My state: ' . $this->someState;
}
}
class Something {
public __construct(Base $base) { $this->base = clone $base; }
public function sayHello() { $this->base->sayHello(); }
private $base = null;
}
$derived = new SpyDerived;
$something = new Something($derived);
$derived->setSomeState(true);
$something->sayHello();
?>
You see this? $base is cloned. Something::$base is a copy.
So in PHP, what would you do to solve that problem?
Simple! Remove that clone, no copies!
Well, in C++, this is the same thing. If you have an object pointer and don't want to clone it, don't actually call the clone method.
We will change your class to, like PHP, contain a reference to the object. We will start by making Something contain a non owning reference:
class Something {
public:
explicit Something(Base& b) : base{b} { }
void sayHello() const { base.sayHello(); }
private:
// we simply contain a reference to the base
Base& base;
};
In C++, a reference does not own the object. If the object is destroyed, all reference pointing to that object will point to a dead object.
As you can notice, your tests stays the same and work:
int main() {
SpyDerived derived;
Something something(derived);
derived.setSomeState(true);
something.sayHello();
}
If you want Something be the owner of Base, then use std::unique_ptr<Base>:
class Something {
public:
explicit Something(std::unique_ptr<Base> b) : base{std::move(b)} { }
void sayHello() const { base->sayHello(); }
private:
std::unique_ptr<Base> base;
};
Beware that the ownership of base should be transferred from the caller to the something class. That transfer is express through that std::move thing, because we are moving the ownership of that resource.
Then in your tests:
int main() {
auto derived = std::make_unique<SpyDerived>();
// We want to keep a non-owning reference of derived
// The star (*) operator of std::unique_ptr returns a reference to the pointed object
auto& derived_ref = *derived;
// We transfer the ownership of derived to the `Something`
Something something(std::move(derived));
// Since derived is a reference to the object pointed by our pointer,
// It will affect the value we found in `Something`, because they are
// both pointing to the same instance.
derived.setSomeState(true);
something.sayHello();
}
Since Something is owner of derived, the non-owning reference derived_ref will point to a dead object if something dies before.

C++ Non-destructible classes

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);
}

Data structure that can hold multiple types of data

Like the title says, I'm looking for some kind of data structure which will allow me to store any type of class into it that I need at the time. For example:
Foo *foo = new Foo();
Bar *bar = new Bar();
someContainer.push_back( foo );
someContainer.push_back( bar );
someContainer.access( 0 )->doFooStuff();
someContainer.access( 1 )->doBarStuff();
Ideally, as I showed there, it would also allow me to access the contents and use their functions/etc.
I want one of these as I am attempting to create an "invisible" memory management system that just requires a class to inherit my memory manager class, and everything will work automagically.
Here is an example of what I want the code to look like:
template< class T >
class MemoryManaged
{
MemoryManaged()
{
container.push_back( this );
}
void *operator new()
{
// new would probably be overloaded for reference counting etc.
}
void operator delete( void *object )
{
// delete would most definitely overloaded
}
T &operator=( T &other )
{
// = overloaded for reference counting and pointer management
}
static SomeContainer container;
}
class SomeClass : public MemoryManaged< SomeClass >
{
// some kind of stuff for the class to work
};
class AnotherClass : public MemoryManaged< AnotherClass >
{
// more stuff!
};
I hope that my code helps make clear what exactly it is I want to do. If someone knows some kind of already-built data structure that would allow me to do this, that would be awesome. Otherwise, I am currently working on building some kind of shambling zombie of a linked list class that uses templated nodes in order to link any type of class to any other type of class. I still have no idea how I'd get it to work yet, and I would love to be spared the blood, sweat, and tears (and hair) it would take to figure out how to make it work.
Have a common base class for all of your multiple types. Have the data structure hold onto pointers of your base class's type.
Take a look at boost::any and boost::variant.
Would some hybrid of template specialization and double-dispatch help? Something like this:
class IContainable;
class Operation
{
public:
template<class ElementType> void Process(ElementType* pEl) {
// default is an unrecognized type, so do nothing
}
};
class IContainable
{
public:
virtual void OperateOn(Operation* pOperation) = 0;
};
class Foo : public IContainable
{
public:
int GetFooCount() { return 1; }
virtual void OperateOn(Operation* pOperation);
};
// specialization of the operation for Foo's
template <> void Operation::Process<Foo>(Foo* pFoo)
{
std::cout << pFoo->GetFooCount() << std::endl;
}
void Foo::OperateOn(Operation* pOperation)
{
pOperation->Process(this);
}
int main()
{
typedef std::vector<IContainable*> ElementVector;
ElementVector elements;
// configure elements;
Operation oper;
for(ElementVector::iterator it = elements.begin();
it != elements.end(); it++)
{
(*it)->OperateOn(&oper);
}
}
If the list of types in the container isn't known at compile time of the operations of the elements on the container, or they are distributed across modules that are not compiled together, then you could instead use dynamic_cast. You'd define a "IFooHandler" class witha pure virtual method called "HandleFoo" that takes a foo pointer. You'd make Operation::Process virtual and have your operation class derive from both Operation and IFooHandler and implement the operation in HandleFoo(). Your Foo::OperateOn method would dynamic_cast(pOperation) and if the result was non-null, it would call HandleFoo() on the IFooHandler pointer you get from the dynamic cast. Otherwise you'd call the generic Operation::Process and it would have some non-type-specific behavior.
Using a std::vector<T*> should work. Indeed, a new class will be created for each instantiation of MemoryManaged. This means that MemoryManaged<Foo> and MemoryManaged<Bar> will be totally different types. Consequently, the static member container will not be common to these two classes. It will be as if you had the two following classes:
class MemoryManagedFoo
{
MemoryManagedFoo()
{
//Here, you know that 'this' is a Foo*
container.push_back(this); //ok, we add 'this' to a container of Foo*
}
static std::vector<Foo*> container;
};
class MemoryManagedBar
{
MemoryManagedBar()
{
//Here, you know that 'this' is a Bar*
container.push_back(this); //ok, we add 'this' to a container of Bar*
}
static std::vector<Bar*> container;
};
As you can see, the static member is not shared by the two instantiations.
Of course, this solution assumes that MemoryManaged will always be used using CRTP, as you described in your question. In other word, this code will work:
class Foo : public MemoryManaged<Foo> { };
but not this one:
class Foo : public MemoryManaged<Bar>
{
// Here, 'container' is a 'vector<Bar*>' and 'this' is a Foo * --> problem
};