3 ms·
uh ? unlike languages such as java, or c#, objects aren't nullable in C++, only pointers to objects. You can't do for instance struct foo { // whate
by jcelerier 8y ago
uh ? unlike languages such as java, or c#, objects aren't nullable in C++, only pointers to objects.
You can't do for instance
struct foo {
// whatever
};
foo my_function() {
return nullptr;
}
and thus,
std::optional<int> my_function() {
return nullptr;
}
does not compile (rightly).
- iBelieve 8y agoWouldn't it be more correct to say that Java and C# don't have nullable objects either, it's just that they're always used via pointers, so any object reference can be nullable, unlike C++, which allows objects to be passed by value and thus not be nullable?
- pjmlp 8y agoC# is not like Java. struct Vector { int x, y; } public class Program { public static void Main() { Vector v = null; } } Also does not compile: "Cannot convert null to 'Vector' because it is a non-nullable value type"
- jcelerier 8y agowell, change that struct into class and it does AFAIK :p Basically, just given `public foo myFunction() { ... }` there's no easy way to know
- winstonewert 8y agoNope. class and struct are almost the same thing in C++ .
- jcelerier 8y agoyes, I was talking about C#.
- winstonewert 8y agosorry, got confused given that the discussion was originally regarding C++
- pjmlp 8y agoSure there is, you will see foo is a struct by simple mouse hovering, no one sane uses C# with Notepad. Structs are value types and cannot be heap allocated like in C++. Doing new foo() will only call the constructor while stack allocating, while in C++ will put it on the heap. Also, the only way structs ends on the heap is by implicit boxing when converting to an interface. Finally, yes structs can be nullable, only when they are declared as such, Typename?.
- cesarb 8y ago> Sure there is, you will see foo is a struct by simple mouse hovering, no one sane uses C# with Notepad. Does mouse hovering work when you're reviewing a diff on gitlab?
- pjmlp 8y agoOn that case, you do just like in C++ and look at the type definition. Unless you can magically understand it is a struct just by looking at the name, instead of a typedef, using definition or even a macro.