Creating a temporary nameless class instance in C++ - c++

Sometimes I need to instantiate a class only to call its one methed. For example to read registry in Qt.
QSettings settings;
settings.setValue( DEST_FOLDER, destDir );
But I use this syntax instead.
QSettings().setValue( DEST_FOLDER, destDir );
It works but I haven't seen any documentation on it, what is it called? I searched 'nameless c++ class' but it doesn't come up. There is anonymous class but I think that's different.
My question is its a little like calling the constructor..is there a name to this kind of syntax? Can someone explain or point me to documentation to this kind of initialization? Dumb question but is it bad to do this?

QSettings().setValue( DEST_FOLDER, destDir );
will give you a default constructed temporary instance of QSettings that will exist until the end of the full expression, in this case the ; at the end of the line, and then call setValue(...) on said temporary.
You can call every constructor you want this way, not just the default constuctor as you did in your example. If e.g. class A has a constructor and a member function fun that take a single int,
A(5).fun(20);
will create a temporary object of type A via A::int(5) and then call A::fun(int i) with i = 20 on it.
This is allowed and safe, whether this actually makes sense depends on what the method you call does in the end.
Note that the class itself is neither nameless nor temporary, only the instance you create is.

"My question is its a little like calling the constructor..is there a name to this kind of syntax?"
Yes, it's called a creating a temporary rvalue
"Can someone explain or point me to documentation to this kind of initialization?"
It's a basic c++ feature, documentation may be given in the C++ standard specification.
"Dumb question but is it bad to do this?"
Totally depends on what features QSettings actually provides, and these kind of calls persist the settings, as you want to do.

Related

How to create pass-by-ref parameter in BlueprintCallable UFUNCTION that doesn't need variable plugged to pin and checks if variable was plugged or no?

What I want to achieve:
A Blueprint Callable function that takes UPARAM(ref) bool& as a parameter which can but doesn't have to be passed inside of Blueprint Graph (variable doesn't have to be plugged into input pin to this node for the graph to compile). And by *asing on if the parameter has been passed or not, the function will behave in a slightly different way.
For example, I was able to create something like this in C++ (pastebin imgur):
void Func(bool& param = *(bool*)0)
{
if (&param == nullptr)
// do something
}
Above code compiles and consistently behaves in VS2022, allows to call Func() without passing any parameters in it and execute code basing on if the parameter has been passed which is the exact behavior that I'm looking for.
However, this code is a C++ undefined behaviour not allowed for UFUNCTIONs. So, when I try to declare something similar as BlueprintCallable UFUNCTION in Unreal, this of course will not compile:
UFUNCTION(BlueprintCallable)
static void Func(UPARAM(ref) bool& param = *(bool*)nullptr);
due to error:
C++ Default parameter not parsed: param "(bool)nullptr"
So my question is:
Is the "behaviour/functionality" that I want to achieve even possible in BlueprintCallable functions?
Is there any workaround to what I've described above? For example in form of macros, custom data containers or function specifiers?
I think summary of my question might be a little bit misleading. I just want to recreate this type of code/behaviour pastebin imgur in Unreal's 'UFUNCTION(BlueprintCallable)'. Yes, I understand that given example is an UB, but this is the closest result to what I want to create. This is just an example.
This question is Unreal Engine / UFUNCTION related. This is not a typical C++ issue. Unreal uses macros for UFUNCTION declaration and compiles in a different way than regular C++ (UFunctions). Because of that pointer cannot be used as parameter in this case as Unreal does not allow it. However pointer would be an actual solution to this question if it were only about pure C++.
Possible but not exact solutions:
meta = AutoCreateRefTerm( "param" ) can be specified in the UFUNCTION declaration. This allows Blueprint Node to have default value in pass-by-ref pin. However, with this approach another condition (bool pin) is needed because it is not possible check if actual variable gets passed or not.
In comments TOptional has been mentioned. This data container is actually something that exactly fits here, but TOptional cannot be used as parameter in BlueprintCallable UFUNCTION due to "Error: Unrecognized type 'TOptional' - type must be a UCLASS, USTRUCT, UENUM, or global delegate.", or at least I don't know how to use it.
My question has been closed as a dupe of Is null reference possible? which isn't true. My question asks for high level functionality in Unreal's Blueprints/UFUNCTIONS that would omit the need of "null reference". Something like TOptional::IsSet

Making default constructor private in Qt custom object

I'm reading this Qt doc page about custom types, and it states the following:
The default constructor, copy constructor and destructor are all required, and must be public, if the type is to be integrated into the meta-object system.
Suppose I have an object that needs to be built with some required parameters, because it has no sense to be built using the default constructor, for example:
struct IntPair
{
IntPair(int first, int second);
~IntPair();
};
To make it available in the Qt Meta Object system, as the doc states, it requires the default constructor. But practically, it has no sense to give the opportunity to build an IntPair object without a pair of integer numbers (sorry for the ugly example).
Is there a way to achieve this without implementing the default constructor? I'm thinking about a sort of friendship between my object and the Qt Meta Object system...
Basically, I cannot understand why the default constructor is needed.
There are two parts to the question:
Achieving a custom Meta Object without implementing a default ctor.
Understanding why a default ctor is required by Qt in this case.
Other respondents have addressed (2) already.
I wish to address (1).
I wrote a class, and I intend for users of this class to call a ctor I wrote which requires several arguments. However, because of the Qt-related requirements, I am forced to add a zero-argument constructor.
It would make me happy to at least make the zero-arg ctor private, so that I could enforce that all user code EXCEPT moc-generated "magic" code will be barred from using that ctor.
Hello, happiness! It is possible.
You can indeed use friendship to make the default ctor private and still use Qt Metatype.
It looks something like this:
class MyClass {
Q_GADGET
Q_PROPERTY(QString text READ text)
public:
MyClass(QString text, bool sometruth, int someint);
QString text() const { return text_; }
private:
// Works in my project using Qt 5.12. (see hints below if it fails for you)
friend struct QtMetaTypePrivate::QMetaTypeFunctionHelper<MyClass, true>;
// Prefer the ctor that takes arguments. This ctor only exists to satisfy Qt.
MyClass();
QString text_;
};
There are two ways you can solve the problem of figuring out WHAT to befriend.
You can mark the ctor private, try to recompile, and scrutinize the compiler error to figure out what other type is trying to access the ctor of your class.
Or, you can put an assert(false); in the body of your ctor, create a binary with debug symbols (including Qt debug symbols), then look at the stack in the debugger when the assertion fails. The stack will show the Qt-internal member-function or free function that called into your ctor. Friend whatever that caller is.
This last method (using the debugger) is what worked for me. (I wasn't fluent enough in compiler-ese to discern which type from the output of the gigantic compiler error was what I needed to add as my friend.)
It has to do with QVariant's (templated) implementation.
Look at qvariant.h in the QT5.5 source code tree, and you'll find this:
T t;
if (v.convert(vid, &t))
return t;
return T();
And also:
old->~T();
new (old) T(t); //call the copy constructor
Hence the need for a public constructor/desctructor, and copy-constructor.
The advantage of all of this is being able to use your custom type in signals/slots (and other meta-object magic), but there are drawbacks like in your situation. It's just a trade-off that you have to live with.
As a workaround, you could have some sort of "init()" method that actually initializes the object after it's constructed. Not as safe/elegant, but it works.
As to why, there's a design reason behind it. It involves a "Identity vs Value" discussion that I think is too long to paste here.
As to how, #AlexanderVX commented on using default values in arguments.
Custom data type should have public default constructors because many parts of the Qt framework will call it to avoid returning null pointers. E.g. QVariant and containers accessors (e.g. QHash::value()).
In your case IntPair() : IntPair(0,0) { } should be nice, isn't it ?
In many cases it is convenient to hold data in objects impementing Qt's implicit sharing pattern (see http://doc.qt.io/qt-5/implicit-sharing.html), in which case the default constructor may easily initialize with QSharedDataPointer(0) and every accessor return a default value when pointer is null (e.g. 0 for an int, QString() for a QString, etc.), guess what: every accessor will be able to provide a default value by calling the public default constructor of the data type because it is required to have one :-).

Lua/C++ binding from scratch

I'm new to Lua, and trying to understand some of the fundamentals. Something I want to understand is binding Lua to C++ instances.
I am not interested in third party libraries, I want to understand this at a more fundamental level - thanks :)
Here are my questions:
My assumption based on what I have read, is that Lua can only bind to static C functions. Is this correct?
Does that mean that to bind an instance of a C++ class, I'd first need to write static functions for each method and property getter/setter I want, accepting an instance pointer as a paramter.
I'd register these functions with Lua.
I'd pass Lua a pointer to the instance of the C++ class.
From Lua I'd call one of the registered functions, passing the C++ instance pointer.
The static function dereferences the pointer, calling the equivalent method.
Does this make sense? Or have I gotten something wrong?
Thanks for reading this far.
This is right up my ally.
1) Lua ... it doesn't really bind to stuff, what you need to do is "play nice with Lua" and that requires knowing a bit about how Lua works.
I REALLY suggest reading http://luaforge.net/docman/83/98/ANoFrillsIntroToLua51VMInstructions.pdf that.
That tells you about EVERYTHING Lua is actually able to do. So the functions Lua gives you let you manipulate just those structures.
After that everything makes a lot more sense.
Why this answer should end here
Your questions after 1 are all wrong. and 1 is semantically wrong, a static function just has internal/weak linkage. I guess you mean "not a method"
2) Not really, remember you have that nice "self"/"this" identity with objects (and lua with tables/meta-tables) - you don't bind to methods.
You want Lua to call some function of yours with a "self" argument, that "self" (whatever it may be, a simple integer ID, or a void* if you're feeling dangerous) should tell you what ojbect you are working with.
3/4/5/6 don't really make sense, read that document :) Comment in reply to this if you need more or have something more specific, it's not a bad question btw it's just naive

C++ Detecting an implicit cast of 0 to a class

I am calling a function in a API that returns a Answer object. Under some conditions, the API will return EMPTY_answer, which is defined as such:
#define EMPTY_answer ((Answer)0)
of course, attempting to access a Answer variable or function from an EMPTY_answer object crashes the application.
Trying to test for it using if(lAnswer == EMPTY_answer) also crashes the application. Is there any way to detect if the API is returning EMPTY_answer?
Edit:
I didn't code the api and I can't modify it in any way, I'm just digging through .h files trying to figure this out. And yes, I am aware that casting 0 to a class is a bit too creative to put it mildly. I just noticed that the == operator is overridden
(...)
class ExportedByJS0CORBA Answer
{
(...)
int __stdcall operator==(Answer *ipt) const;
}
the function being called is
static SubClassOfAction Query();
I'm simplifying names and quite a few layers of inheritance
To be more precise, it crashes with a Segmentation Fault.
Instead of doing a very ugly cast which is almost guaranteed to trigger undefined behavior, just make a static global variable which is used as the "empty" answer. You don't need to use this object in any way, just make it exist so it can be used as a sentinel.
In Answer.h:
extern const Answer EMPTY_answer;
In Answer.cpp:
const Answer EMPTY_answer; // use any constructor parameters that will be appropriate
If Answer is a class type, as the text of your questions suggest, then (Answer) 0 will construct a temporary Answer object using the constructor that accepts 0 as an argument (apparently such constructor exists). In this case attempting to access the members of that object will not crash anything, unless Answer class is specifically implemented to crash in this case (intentionally or unintentionally). So your "Of course..." claim makes no sense whatsoever. There's no immediate reason for such code to crash.
If you observe crashed in someAnswer == EMPTY_answer comparison, that would either mean that the implementation of == operator is buggy, or that either the LHS or the RHS are not valid objects. For example, it might turn out that it is illegal (by design) to construct an Answer object by conversion from 0. If so, then you should simply stop using (Answer) 0 in your code and find another, correctly supported object value to indicate an empty answer.
your original method of just checking for EMPTY_answer is the right way to solve this. Your real problem is why that crashes. What type is lAnswer? Or Answer for that matter... you can't cast 0 to a class like that.

How do I pass reference types between webservices?

I'm having a bit of difficulty passing a reference type between webservices.
My set up is as follows.
I have a console application that references two web-services:
WebServiceOne
WebServiceTwo
WebServiceOne declares the details of a class I am using in my console application...let's call it MyClass.
My console application calls WebServiceOne to retrieve a list of MyClass.
It then sends each MyClass off to WebServiceTwo for processing.
Within in the project that holds WebServiceTwo, there is a reference to WebServiceOne so that I can have the declaration of MyClass.
The trouble I'm having is that, when I compile, it can't seem to determine that the MyClass passed from the console application is the same as the MyClass declared in WebServiceOne referenced in WebServiceTwo.
I basically get an error saying Console.WebServiceOne.MyClass is not the same as MyProject.WebServiceOne.MyClass.
Does anyone know if doing this is possible? Perhaps I'm referencing WebServiceOne incorrectly? Any idea what I might be doing wrong?
My only other option is to pass each of the properties of the reference type directly to WebServiceTwo as value types...but I'd like to avoid that since I'd end up passing 10-15 parameters.
Any help would be appreciated!
I had a chat with one of the more senior guys at my work and they proposed the following solution that has worked out well for me.
The solution was to use a Data Transfer Object and remove the reference to WebServiceOne in WebServiceTwo.
Basically, in WebServiceTwo I defined a representation of all the value type fields needed as BenefitDTO. This effectively allows me to package up all the fields into one object so I don't have to pass each of them as parameters in a method.
So for the moment, that seems to be the best solution...since it works and achieves my goal.
It's likely that I didn't explain my question very well...which explains why no one was able to help...
But thanks anyway! :-)
Move the types to a separate assembly and ensure that both services use this. In the web service reference there is probably some autogenerated code called Reference.cs. Alter this to use your types.
Edit: To reflect comments
In that case take the reference.cs from that web service you cannot control use it as the shared type.
Your error message explains the problem. The proxy class on the client side is not the same type as the original class on the server side, and never will be. Whether it's a reference type or a value type is irrelevant to how it works.
I don't quite understand what your exact problem is, but here are a few guesses:
If you are trying to compare two objects for equality, then you will have to write your own compare function that compares the values of each significant property/field in turn.
If you are trying to copy an object from one service to the other, then you will have to write your own copy function that copies the values of each significant property/field in turn.
If you were using WCF, you would have the option of bypassing all this and just sharing one class definition between the client and both services.