ABI-compatible shared_ptr implementation - c++11

I am working on a COM-style complier cross-compatible plugin framework relying on compatible virtual table implementations for ABI compatibility.
I define interfaces containing only pure virtual member functions and an overridden delete operator to channel destruction to the place of implementation.
This works well with extern "C" factory functions instantiating the plugin implementation of the interface and returning an interface-type pointer.
However, I was wondering if smart pointers wouldn't be a more modern way to manage the lifetime of the plugin object. I think I have actually managed to
create a standard-layout shared_ptr/weak_ptr that uses a reference count object defined and implemented the same way as the plugin interfaces.
It looks something like this:
class IRefCount
{
public:
virtual void incRef() = 0;
virtual void decRef() = 0;
virtual bool incRefIfNZ() = 0;
virtual void incWRef() = 0;
virtual void decWRef() = 0;
virtual long uses() const = 0;
protected:
~ref_count_base() = default; //prohibit automatic storage
}
template <typename Ty>
class shared_ptr
{
private:
Ty* ptr_;
IRefCount* ref_count_;
public:
//member functions as defined by C++11 spec
}
Three questions:
Before the smart pointer the factory function looked like this:
extern "C" IPlugin* factory() { try { return new Plugin(); } catch (...) { return nullptr; } }
Now, it looks like this:
extern "C" shared_ptr<IPlugin> factory() { try { return shared_ptr<IPlugin>(new Plugin()); } catch (...) { return nullptr; } }
VS2013 is giving me warning C4190: 'factory' has C-linkage specified, but returns UDT 'shared_ptr' which is incompatible with C. According to MSDN this is OK, provided that both caller and callee are C++.
Are there any other potential issues with returning standard-layout objects from "C" linkage functions?
Calling conventions. Should I be specifying __stdcall for all pure-virtual interface functions and factory functions?
I am using <atomic> for the reference count. I am writing platform-independent code and I have not yet tried compiling for ARM. According to http://infocenter.arm.com/help/index.jsp?topic=/com.arm.doc.dht0008a/ch01s02s01.html armcc does not implement std::atomic. Any better compilers/stl out there?

Related

How to make an internal header when using interface + templates for dependency injection

In this blog post about dependency injection in C++, the author explain a hybrid approach that uses both templates and interfaces as follows:
ICar.h (publicly visible):
#pragma once
struct ICar
{
virtual void Drive() = 0;
virtual ~ICar() = default;
};
std::unique_ptr<ICar> MakeV8Car();
std::unique_ptr<ICar> MakeV6Car();
Car.h (internal):
#pragma once
#include "ICar.h"
template <typename TEngine>
class Car : public ICar
{
public:
void Drive() override
{
m_engine.Start();
// drive
m_engine.Stop();
}
private:
TEngine m_engine;
};
Car.cpp:
#include "Car.h"
#include "V8Engine.h"
#include "V6Engine.h"
std::unique_ptr<ICar> MakeV8Car()
{
return std::make_unique<Car<V8Engine>>();
}
std::unique_ptr<ICar> MakeV6Car();
{
return std::make_unique<Car<V6Engine>>();
}
All of which makes good sense to me, except for the internal part. Let's assume I've created a shared object from the above.
How is Car.h private in the context of this shared object?
I've read on the meaning of a private header in the answer which states:
Keep your data in MyClassPrivate and distribute MyClass.h.
Presumably meaning to not distribute MyClass_p.h, but how does one avoid distributing a header file and still have the .so work?

Inferencing the typename of 'this' in a virtual method

I am aware of the lack of reflection and basic template mechanics in C++ so the example below can't work. But maybe there's a hack to achieve the intended purpose in another way?
template <typename OwnerClass>
struct Template
{
OwnerClass *owner;
};
struct Base
{
virtual void funct ()
{
Template <decltype(*this)> temp;
// ...
}
};
struct Derived : public Base
{
void whatever ()
{
// supposed to infer this class and use Template<Derived>
// any chance some macro or constexpr magic could help?
funct();
}
};
In the example, Derived::whatever() calls virtual method Base::funct() and wants it to pass its own class name (Derived) to a template. The compiler complains "'owner' declared as a pointer to a reference of type 'Base &'". Not only does decltype(*this) not provide a typename but a reference, the compiler also can't know in advance that funct is called from Derived, which would require funct() to be made a template.
If funct() was a template however, each derived class needs to pass its own name with every call, which is pretty verbose and redundant.
Is there any hack to get around this limitation and make calls to funct() infer the typename of the calling class? Maybe constexpr or macros to help the compiler infer the correct type and reduce verbosity in derived classes?
You should use CRTP Pattern (Curiously Recurring Template Pattern) for inheritance.
Define a base class:
struct CBase {
virtual ~CBase() {}
virtual void function() = 0;
};
Define a prepared to CRTP class:
template<typename T>
struct CBaseCrtp : public CBase {
virtual ~CBaseCrtp() {}
void function() override {
using DerivedType = T;
//do stuff
}
};
Inherit from the CRTP one:
struct Derived : public CBaseCrtp<Derived> {
};
It should work. The only way to know the Derived type is to give it to the base!
Currently, this can't be done. Base is a Base and nothing else at the time Template <decltype(*this)> is instantiated. You are trying to mix the static type system for an inheritance hierarchy inherently not resolved before runtime. This very same mechanism is the reason for not calling virtual member functions of an object during its construction.
At some point, this limitation might change in the future. One step towards this is demonstrated in the Deducing this proposal.

C++ using namespaces for versioning can cause inheritance problems with overrides

We are trying to namespace the versions of our API with namespaces, although we figured that we will be getting some problems with virtual functions :
namespace v1 {
class someParam {
public:
someParam() {};
virtual ~someParam() {};
};
class someClass {
public:
someClass() {};
virtual ~someClass() {};
virtual bool doSomething(someParam a);
};
bool someClass::doSomething(someParam a)
{
return true;
}
}
namespace v2 {
class someParam : public v1::someParam {
public:
bool doParamStuff();
};
bool someParam::doParamStuff()
{
return true;
}
}
// Type Aliasing for v2 API
using someClass = v1::someClass;
using someParam = v2::someParam;
// SOME OTHER PROGRAM
class plugin : public someClass
{
public:
plugin() {};
virtual ~plugin() {};
bool doSomething(someParam a) override;
};
In this specific case, we are creating extension of existing classes to allow binary compatibility. Although, we get a compilation error for plugin::doSomething because of the override keyword as it is not overriding someClass::doSomething because:
plugin::doSomething(v2::someParam) vs someClass::doSomething(v1::someParam).
Is there any way to fix up the plugin without explicitely using v1 for someParam in plugin class ? Ideally, nothing should be done on the plugin side, and without having to create v2::someClass
This:
virtual bool doSomething(::v1::someParam a)
specifies a binary (and C++) interface. You cannot override it with
virtual bool doSomething(::v2::someParam a)
as that is a different type. They are not compatible. These signatures are unrelated.
When you update someParam, you must also update every interface that uses someParam, and then every interface that uses those interfaces, etc.
So, in namespace v2:
class someClass: ::v1::someClass {
public:
virtual bool doSomething(::v1::someParam a) override final;
virtual bool doSomething(someParam a);
};
and in doSomething(v1::someParam) describe how to generate a v2::someParam and pass it to the new doSomething.
If you cannot do this, you instead have to do this:
class someClass {
public:
virtual bool doSomething(someParam a);
};
and make v2::someClass a type unrelated to v1::someClass.
Regardless, you do
using someClass = v2::someClass;
Now, instead of using using declarations, you can instead conditually use inline namespaces.
When you update a version, make the current version the inline namespace. The others are normal namespaces.
Code will now silently start using the inline namespace that is "current".
You can import types from previous namespaces by using symbol = ::library_ns::v1::symbol; This should only be done when that type is unchanged, as well as all of its parameters.
Now, if your ::v2::someParam is only a helper, you can split someParamArg from someParamInstance types.
someParamArg would then be the argument type of the root of the someParam heirarchy (::v1::someParam), while someParamInstance would be ::v2::someParam; what people should create when they want to use it.
In this case, someParamArg needs to be able to consider every state of someParamInstance, even those from later versions. Hence this only works if ::v2::someParam is essentially a helper, or if it supports internal value-type polymorphism.

Replacement of Poco::AutoPtr with boost

I am trying to replace Poco::AutoPtr with some alternative in boost. Here is what I have discovered so far:
What I have: below classess are being used with Poco::AutoPtr. They need to implement reference counted method with implementing duplicate() and release() methods.
I am using above referece_counted.h and Poco::AutoPtr in a complex class hierarchy with multiple inheritance and c++ diamond problems.
A simplified version of classes would look something like this
class A : virtual public ReferenceCounted
{
...
}
class B : public A
{
...
}
class C : public A
{
...
}
class D : public A, B
{
...
}
and the list goes on for few more level deep. I know that this needs to be refactored with a simplified hierarchy but I wanna remove Poco::AutoPtr first with proper replacement in boost:
What I have found so far:
I have found that boost::intrusive_ptr is the closest smart pointer that can be a good replacement of Poco::AutoPtr.
I am however not able to implement the proper solution with this because the intrusive_ptr requires intrusive_ptr_add_ref and intrusive_ptr_release methods created specifically for each class with which I need to use the pointer. I tried using templates but still not having proper solution at hand.
Also one more issue is that I need to typecast from base to derived class many times.
is intrusive_ptr is the correct smart pointer for this usage ? and if yes.. can anybody give me suggestion regarding how to use the same ?
I am however not able to implement the proper solution with this
because the intrusive_ptr requires intrusive_ptr_add_ref and
intrusive_ptr_release methods created specifically for each class with
which I need to use the pointer.
No-no. It is should not be hard. As Boost documentation says:
On compilers that support argument-dependent lookup,
intrusive_ptr_add_ref and intrusive_ptr_release should be defined in
the namespace that corresponds to their parameter; otherwise, the
definitions need to go in namespace boost.
Try this: main.cpp (built ok with "g++ main.cpp -o main -lboost_system")
#include <boost/intrusive_ptr.hpp>
class MyObject
{
public:
void duplicate(){
// ...
}
void release(){
// ...
}
};
namespace boost {
template <class T>
void intrusive_ptr_add_ref( T * po ) {
po->duplicate(); // your internal realization
}
template <class T>
void intrusive_ptr_release( T * po ) {
po->release();
}
}
int main(int argc, char **argv)
{
// ...
boost::intrusive_ptr<MyObject> ptr( new MyObject );
boost::intrusive_ptr<MyObject> ptr2 = ptr; // should work
}

C++0x Member initialization without a constructor

In N3257 I found an example using initializing members without a constructor, which is fine. I guess that is possible, because it is a POD.
template<typename T>
struct adaptor {
NonStdContainer<T>* ptr; // <- data member
T* begin() { return ptr->getFirst(); }
T* end() { return ptr->getLast() + 1; }
};
void f(NonStdContainer<int>& c) {
for (auto i : adaptor<int>{&c}) // <- init
{ /* ... */ }
}
When I played around with this example I replaced the * with a &, because I don't like raw pointers:
template<typename T>
struct adaptor {
NonStdContainer<T>& ptr; // <- data member, now REF
T* begin() { return ptr->getFirst(); }
T* end() { return ptr->getLast() + 1; }
};
void f(NonStdContainer<int>& c) {
for (auto i : adaptor<int>{c}) // <- init
{ /* ... */ }
}
This was fine and compiled without warning with GCC-4.7.0.
Then I got curious about the initialization of PODs and what might have changed with C++0x.
There I found Bjarnes FAQ. He says there that PODs may contain pointers, but no references.
Ops, now I wonder:
Do I have non-POD-object here, which the compiler can initialize without a constructor anyway and I just miss which mechanisms are used here?
or Is the GCC-4.7.0 behaving non-std by letting me initializing the ref this way?
or has there been a change in the std since Bjarnes FAQ that also allows references in PODs?
Update: I found aggregates in the current std (8.5.1 Aggregates [dcl.init.aggr]), but references are not mentioned there, so I am not sure how they relate to this
Quoting the standard [dcl.init.aggr]:
An aggregate is an array or a class (Clause 9) with no user-provided
constructors (12.1), no brace-or-equal- initializers for non-static
data members (9.2), no private or protected non-static data members
(Clause 11), no base classes (Clause 10), and no virtual functions
(10.3).
When an aggregate is initialized by an initializer list, as speciļ¬ed
in 8.5.4, the elements of the initializer list are taken as
initializers for the members of the aggregate, in increasing subscript
or member order. Each member is copy-initialized from the corresponding initializer-clause...
That means you have an aggregate here, aggregates can be initialized how you do it. PODs have nothing to do with it, they are really meant for communication with eg. C.
Copy-initialization of a reference with a variable is certainly legal, because that just means
T& ref = c;
Do I have non-POD-object here, which the compiler can initialize without a constructor anyway and I just miss which mechanisms are used here?
Yes, the object is non-POD.
Is the GCC-4.7.0 behaving non-std by letting me initializing the ref this way?
No.

Resources