Replace void rvalue reference - c++

I am writing a kind of message passing interface, where a frontend request a variable of type Var to a backend. In the most simple form, it reads:
Var backend();
Var interface() {return backend();}
Var frontend() {return interface();}
Unfortunately, although interface implementation is aware of type Var, its signature is not. Had a void rvalue reference existed in c++, I would use something like
void&& interface();
with proper casting, because I want this process to stay copy free as most as possible, and I do not want Var constructor to be called. I came up with this hack:
void interface(void* p) {new (p) Var(backend());}
Var get()
{
char hack[sizeof(Var)];
impl_get(static_cast<void*>(&hack));
return std::move(*reinterpret_cast<A*>(hack));
}
Which, as far as I know, only calls the move constructor of Var (if defined). Is this solution standard and safe and is there any cleaner way of doing that?

Related

Code simpler than lambda for a call in constructor that uses an output parameter function for initializing a const member

In the header, I have
class CSomeClass
{
const GUID m_guid;
public:
CSomeClass();
///...
}
And in the source file
CSomeClass::CSomeClass()
, m_guid(
[]() {
GUID g;
::CoCreateGuid(&g);
return g;
}()
)
{
}
As you know Guids can be used as identifications not meant to be changed. Given the ::CocreateGuid() function provides what I want as an output parameter, instead of returning it, I cannot use directly a simple call to the function for initializing the m_guid member field, that is constant.
So, a consequence of its constness, is that it must be initialized before the opening bracket in initializer list, and therefore not be simply assigned with a call to ::CocreateGuid() in the constructor body.
Is there a simpler way to initialize it than this lambda expression?
When the lambda expression is correct, I would use a helper function for that:
GUID create_guid()
{
GUID g;
::CoCreateGuid(&g);
return g;
}
CSomeClass::CSomeClass() : m_guid(create_guid()) {}
In addition, create_guid() has a meaning by itself and could be reused (even if making it a implementation detail is possible/correct).
You should consider wrapping the GUID in its own class:
class CGUID
{
public:
CGUID()
{
CoCreateGuid(m_guid);
}
const GUID& guid() const { return m_guid; }
// Maybe some useful functions:
bool operator==(const CGUID&) const;
private:
GUID m_guid;
};
Now you can use the above as a member:
class CSomeClass
{
const CGUID m_guid;
...
Here we abstract your pattern:
template<class A>
A co_make( HRESULT(*f)(A*) {
A a;
HRESULT hr = f(&a);
Assert(SUCCEEDED(hr));
if (!SUCCEEDED(hr))
throw hr;
return a;
}
CSomeClass::CSomeClass()
m_guid(
co_make(&::CoCreateGuid)
)
{}
where we detect failure and assert then throw if that is the case.
I'm not sure this is simpler.
Really, write a GUID make_guid() function, stick it in some header, and call it.
Your proposal is the simplest way to initialize the constant instance member.
Don't get scared of lambdas, as a matter of fact, in general it is a new style recommendation to use lambdas for complex initializations of constants and references because they share the property of only being initialized at the point of declaration (or instance member initialization in the initializer list).
Furthermore, your code triggers the "named return value optimization" and there is no copy construction at the return from the lambda.
The interface to CoCreateGuid is deficient because it requires an output argument.
If you insist on not using the lambda, I think the next most practical alternative is to, in the constructor body, de-constify using const_cast to pass it to CoCreateGuid.
Mind you that one you enter the body of a constructor the language considers all individual members to have been properly initialized, and will invoke destructors for them should an exception happens, this makes a very big difference whether something is initialized in the initializer list or left with a binary pattern of garbage.
Finally, unfortunately you can't just call CoCreateGuid with a de-constified reference to m_guid in the lambda, because the lambda will still return a value and that will overwrite the member. It is essentially the same as what you already wrote (with the exception of the default constructor of g)
It would be simpler if you declare m_guid as a mutable instance member as opposed to const. The difference is that mutable are like a const for users of a class but a perfectly fine lvalue within the class

Handle a value being changed in a c++ struct

I have a struct that describes how the system should be initialised. I then have a method that returns a reference to said struct so that the user of the final system can change certain options after initialisation. I wish to detect when a value is changed and tell the component parts of the system to check for options they depend on to see if they've been changed and update themselves accordingly.
I believe such a thing is possible by overloading an operator or something similar. I don't really mind about overhead and what the detection & updating code looks like, I just want the syntax for changing an option to look clean, and for the user to not have to call a updateOptions() function after changes or anything.
Firstly, is this even possible? Secondly, if it is, how would I go about it?
I will assume your struct is named Fun
Solution 1: Add getter, setter and notify
I would write a getter and a setter for each properties of the said struct. It would look like this:
struct Fun {
Fun(System& sys): system{sys} {}
void setGun(int g) {
gun = g;
notify();
}
int getGun() {
return gun;
}
void notify() {
system.updated();
}
private:
System& system;
int gun;
};
Of course, the reference can be a pointer and of course, you will have to separate the struct to a header and cpp file.
Solution 2: write a get and set for the struct Fun
The advantage of this solution is that it might be the fastest, and of course the cleanest one.
struct System {
void setFun(Fun f) {
if (f != fun) {
// update only if different
updated();
}
// it may be faster if Fun allocates resources
fun = move(f);
}
// do not return by reference
Fun getFun() const {
return fun;
}
private:
Fun fun;
};
In many cases, changing a single item can cause the entire setting to become invalid but changing 2 or 3 can be a valid setting.
If this is the case, you can should create a getter/setter function pair. The getter function will return a copy of the struct and the setter function will effectively be an updateSetting function.
This has very little overhead and is more robust than having a getter/seeter per item.
If I were you, I would emit an appropriate boost signal in the setter function for each option, and have subscribers sign up for these signals. I would use a class instead of a struct for clarity, because you'll want everything to be private except for exposed signals, setters and getters.
"I have a struct that describes how the system should be initialised. I then have a method that returns a reference to said struct so that the user of the final system can change certain options after initialisation."
That's probably the wrong approach. Better use getter/setter functions for the single properties, such your class can control, how to react on property changes.
Another way would be to let the client retrieve a const reference to your interned properties struct member variable, make a copy of it, change that one and pass it back with a setter (update) function. This would make the process much clearer for the client, than having to call an extra update() function.

pass lambda expression as member function pointer in c++

I have a framework function which expects an object and a member function pointer (callback), like this:
do_some_work(Object* optr, void (Object::*fptr)()); // will call (optr->*fptr)()
How can I pass a lambda expression to it? Want to do somethink like this:
class MyObject : public Object
{
void mystuff()
{
do_some_work(this, [](){ /* this lambda I want to pass */ });
}
};
The meaning of it all is to not clutter the interface of MyObject class with callbacks.
UPD
I can improve do_some_work in no way because I don't control framework and because actually it isn't one function, there're hundreds of them. Whole framework is based on callbacks of that type. Common usage example without lambdas:
typedef void (Object::*Callback)();
class MyObject : public Object
{
void mystuff()
{
do_some_work(this, (Callback)(MyClass::do_work));
}
void do_work()
{
// here the work is done
}
};
SOLUTION Here's my solution based on Marcelo's answer:
class CallbackWrapper : public Object
{
fptr fptr_;
public:
CallbackWrapper(void (*fptr)()) : fptr_(fptr) { }
void execute()
{
*fptr_();
}
};
class MyObject : public Object
{
void mystuff()
{
CallbackWrapper* do_work = new CallbackWrapper([]()
{
/* this lambda is passed */
});
do_some_work(do_work, (Callback)(CallbackWrapper::execute));
}
};
Since we create the CallbackWrapper we can control it's lifetime for the cases where the callback is used asynchonously. Thanks to all.
This is impossible. The construct (optr->*fptr)() requires that fptr be a pointer-to-member. If do_some_work is under your control, change it to take something that's compatible with a lambda function, such as std::function<void()> or a parameterised type. If it's a legacy framework that isn't under your control, you may be able to wrap it, if it's a function template, e.g.:
template <typename Object>
do_some_work(Object* optr, void (Object::*fptr)());
Then, you can implement a wrapper template:
template <typename F>
void do_some_work(F f) {
struct S {
F f;
S(F f) : f(f) { }
void call() { f(); delete this; }
};
S* lamf = new S(f);
do_some_work(lamf, &S::call);
}
class MyObject // You probably don't need this class anymore.
{
void mystuff()
{
do_some_work([](){ /* Do your thing... */ });
}
};
Edit: If do_some_work completes asynchronously, you must allocate lamf on the heap. I've amended the above code accordingly, just to be on the safe side. Thanks to #David Rodriguez for pointing this out.
There are deeper problems with the approach that you are trying to take than the syntactical mismatch. As DeadMG suggests, the best solution is to improve the interface of do_some_work to take a functor of some sort (std::function<void()> in C++11 or with boost, or even a generic F on which operator() is called.
The solution provided by Marcelo solves the syntactical mismatch, but because the library takes the first element by pointer, it is the responsibility of the caller to ensure that the object will be alive when the callback is executed. Assuming that the callback is asynchronous, the problem with his solution (and other similar alternatives) is that the object can potentially be destroyed before the callback is executed, causing undefined behavior.
I would suggest that you use some form of plimp idiom, where the goal in this case would be to hide the need for callbacks (because the rest of the implementation might not need to be hidden you could use just another class to handle the callbacks but store it by value, if you don't want do have to dynamically allocate more memory):
class MyClass;
class MyClassCallbacks {
MyClass* ptr;
public:
MyClassCallbacks( MyClass* ptr ) : ptr(ptr) {}
// callbacks that execute code on `ptr`
void callback1() {
// do some operations
// update *ptr
}
};
class MyClass {
MyClassCallbacks callbackHandler;
public:
void mystuff() {
do_some_work( &callbackHandler, &MyClassHandler::callback1 );
}
};
In this design, the two classes are separated but represent a unique single entity, so it is fine to add a friend declaration and let MyClassCallbacks access the internal data in MyClass (both of them are one single entity, divided only to provide a cleaner interface, but coupling is already high, so adding the extra coupling requiered by friend is no problem).
Because there is a 1-1 relationship between MyClass and MyClassCallbacks instances, their lifetimes are bound and there would be no lifetime issues, except during destruction. During destruction you must ensure that there is no callback registered that can kick in while the MyClass object is being destroyed.
Since you are at it, you might want to walk the extra mile and do a proper pimpl: move all of the data and implementation into a different type that is held by pointer, and offer a MyClass that stores a pointer and offers just the public functions, implemented as forwarders to the pimpl object. This could be somehow tricky as you are using inheritance, and the pimpl idiom is a bit cumbersome to implement on type hierarchies (if you need to extend MyClass, deriving from Object could be done in the pimpl object, rather than the interface type).
I don't think you can do that. Your do_some_work() is declared to accept pointer to methods of class Object, so such should be provided. Otherwise optr->*fptr is invalid since the lambda is not member of Object. Probably you should try using std::function and adding the needed members of Object in its closure.
You must use std::function<void()>. Both function and member function pointers are highly unsuited to being callbacks.

C++ object function to function pointer

I'm using a C library inside my C++ app. The library has a function with the following signature:
void awe_webview_set_callback_js_callback(awe_webview* webview, void (*callback)(awe_webview* caller, const awe_string* object_name, const awe_string* callback_name, const awe_jsarray* arguments));
I'm trying to set a function as a call back and I'd like to be able to use the following class member function
void BattleScreen::HandleWebViewCallbacks(awe_webview* WebView, const awe_string* object, const awe_string* callback, const awe_jsarray* arguments)
{
//handling code
}
I can't bind it directly and based on here http://www.parashift.com/c++-faq-lite/pointers-to-members.html#faq-33.2 I have a possible solution where I'd create a static member to handle the callback (since based on that site, it should be fine) and add a static instance of this class for the static member to call on.
i.e. add the following to BattleScreen:
static BattleScreen* callbacktarget;
static BattleScreen::TopLevelHandleWebViewCallbacks(awe_webview* WebView, const awe_string* object, const awe_string* callback, const awe_jsarray* arguments)
{
callbacktarget->HandleWebviewCallbacks(WebView, object, callback, arguments);
}
bind it in the constructor like so:
awe_webview_set_callback_js_callback(this->GetWebView(), static_cast<void (*)(awe_webview*, const awe_string*, const awe_string*, const awe_jsarray*)>(&BattleScreen::TopLevelHandleWebViewCallbacks));
and assign the object to callbacktarget in the constructor.
BattleScreen::callbacktarget = this;
The problem is I have no way of knowing how many of these classes I will have at any one time (It'll be minimal but possibly greater then 1). I considered making the callbacktarget a vector of BattleScreen* that i can iterate through inside TopLevelHandleWebViewCallbacks and compare like so:
if (callbacktargets[index]->GetWebview() == WebView)
{
callbacktargets[index]->HandleWebviewCallbacks(WebView, object, callback, arguments);
}
but the problem here is that I'm only comparing the awe_webview pointers which seems like a really bad idea. The library is closed source and the awe_webview's are C constructs so I can't see what makes them up and if there are any properties that would make a more suitable comparison. Is there a good solution to this?
If I'm being unclear or you need additional information let me know.
Thanks in advance
The fact that callbacks receive awe_webview pointer more or less proves that comparing them is what they expect you to do.
However, I would modify your solution to use a global map between webviews to BattleScreens:
static std::map<awe_webview*, BattleScreen*> gWebViewBattleScreen;
Then have one global callback that picks the BattleScreen object from it and calls its method:
static void webviewCallback(awe_webview* caller, ......)
{
if (gWebViewBattleScreen.find(caller) != gWebViewBattleScreen.end())
gWebViewBattleScreen[caller]->HandleWebViewCallbacks(......)
}
Nice libraries allow you to pass a context pointer with the callback, so you can assign something like BattleObject* to each callback you set:
void set_nice_callback(void (*callback)(Params params, void* context), void* context);
The library you are using does not seem to be very nice :) You may want to point its developers to this.
Three solution:
Verify that the library doesn't allow you to bind arbitrary 'context' pointer to each awe_webview. They usually do. If it does, store there the pointer to BattleScreen and when the static callback is called, retrieve this pointer from the 'context' of webview and call the member function on this pointer.
Use a global map<awe_webview*, BattleScreen*>. In the static callback, find the BattleScreen corresponding to the webview. Requires locking of the global map, not pretty.
Note: using a pointer to webview as a unique id is almost surely OK. It's always unique.
Use thunks (e.g. http://www.codeproject.com/KB/cpp/thunk32.aspx).

C++ Singleton class returning const reference

I have an a class which is singleton as defined follows
class myData {
private:
myData (void); // singleton class.
// Copy and assignment is prohibted.
myData (const myData &);
myData & operator=(const myData &);
static myData* s_pInstance;
public:
~myData (void);
static const myData & Instance();
static void Terminate();
void myFunc() { cout << "my function..." ;}
};
// In cpp file.
myData* myData::s_pInstance(NULL);
myData::myData(){}
myData::~myData()
{
s_pInstance = NULL;
}
const myData& myData::Instance()
{
if (s_pInstance == NULL)
{
s_pInstance = new myData();
}
return *(s_pInstance); // want to avoid pointer as user may deallocate it, so i used const referense
}
void main() {
(myData::Instance()).myFunc();
}
I am getting following error
error C2662: 'myData::myFunc' : cannot convert 'this' pointer from 'const myData' to 'myData&'
how to avoid above problem and call a function from Instance function which is returning const reference?
Thanks!
You'd want to declare func() as a constant member function, so the compiler knows it won't violate the const'd return value from the instance() function.
You could instead also make the instance() function return a 'regular' reference as apposed to a const one.
So either turn:
void myFunc() into void myFunc() const
Or turn:
const myData& myData::Instance() into myData& myData::Instance()
If you are calling a function on a const reference, the function you call must also be const, in your case void myFunc() const.
Otherwise you might return a non-const reference, if that works better.
The error says that myData::Instance() is a const instance of the class, and it can't call myFunc() on that, because myFunc() might change the instance, and you can't change a const instance.
Of course, you know that myFunc() can't really change the instance, but you must advertise this fact, as follows:
void myFunc() const { cout << "my function..." ;}
Avoiding the whole discussion of whether Singleton is a good to have pattern or the source of all evil, if you are actually implementing a singleton, chances are that const correctness will not work there as you expect it, so you should be aware of some pitfalls.
First your error: your Instance() static member returns a const reference, and that means that you can only perform operations that do not modify the object, i.e. call member functions marked as const, or use public members if present in a way that do not modify their values. My suggested solution is modify Instance() to return a non-const reference, rather than making func() const as others suggest.
Now for a longer explanation to the problem of const-correctness in general when applied to your particular Singleton problem. The basic problem is that when you implement a type, you divide those members that modify the object from those that don't, and you mark the latter as const member functions so that the compiler knows of your promise (allows you to call that method on a constant object) and helps you not break it (complains if you try to modify the state in the definition of the method). A method that is marked as const can be applied to both a constant and non constant object, but a method that is not marked const can only be applied to an object that is not const.
Back to the original piece of code, if you implement a singleton and the only way of accessing the object is by an Instance() method that returns a const reference, you are basically limiting all user code to use only const methods implemented in your interface. That means that effectively either all methods are non-mutating, or they are useless (const_cast should never be used). That in turn means that if you have any non-const operation you want to provide an Instance() method that returns a non-const reference.
You could consider implementing two variants of Instance(), but that will not be really helpful. Overload resolution will not help in user code to determine which version to use, so you will end up having to different methods: Instance(), ConstInstance() (choose your names), which means that it is up to user code to determine which one to use. The small advantage is that in their code, the choice of accessor will help documenting their intended usage, and maybe even catch some errors, but more often than not they will just call the non-const version because it works.