Register a SA Forums Account here!
JOINING THE SA FORUMS WILL REMOVE THIS BIG AD, THE ANNOYING UNDERLINED ADS, AND STUPID INTERSTITIAL ADS!!!

You can: log in, read the tech support FAQ, or request your lost password. This dumb message (and those ads) will appear on every screen until you register! Get rid of this crap by registering your own SA Forums Account and joining roughly 150,000 Goons, for the one-time price of $9.95! We charge money because it costs us money per month for bills, and since we don't believe in showing ads to our users, we try to make the money back through forum registrations.
 
  • Post
  • Reply
Look Around You
Jan 19, 2009

Look Around You posted:

I guess it's strange because in most contexts you expect it to auto-(un)box so intuitively it should work. But it doesn't there.

The following prints "true" for example:

code:
public class Test {
  public static void main(String[] args) {
    Integer i = new Integer(5);
    int j = 4;
    if (i + j == 9) {
      System.out.println("true");
    } else {
      System.out.println("false");
    }
  }
}
e: 8 space indents -> 2 spaces for less huge rear end tabs.

Obviously this is better than undefined behavior of unboxing a null but that's the problem with nullable reference types in a language where you're pretty required to use objects for things.

Adbot
ADBOT LOVES YOU

Sedro
Dec 31, 2008

Internet Janitor posted:

I don't really see what's so strange about it.

code:
((Integer)null).equals(new Object()); // throws NullPointerException
Object.equals and == are two different things in Java. You can swap the operands in my example. Under what other circumstance does the == operator throw a NullPointerException?

Java is trying to auto-unbox the Integer to an int. The same thing happens here:
code:
Integer x = null;
int y = x; // throws NullPointerException
Java performs this implicit conversion that could fail with an exception, without even raising a compiler warning.

PalmTreeFun
Apr 25, 2010

*toot*

JewKiller 3000 posted:

Well, compare to the situation in C, where there are no references. If you want to pass some value to another function, and make it so that any changes made by that function to the value also affect your copy, you can't do that directly. You have to pass the function a pointer to the value. So, all your call sites get &s on the values, the function you're calling has to change the type of that parameter from "whatev param" to "whatev *param", and every param.foo in the function body changes to param->foo.

Kind of annoying, how about the C++ solution? Here you can actually pass by reference. All you do is change the type of the parameter in the receiving function from "whatev param" to "whatev& param". No need to change the call sites, or any of the function body.

Seems nice at first, but think about it from the perspective of a programmer who is calling a bunch of functions, and some of these functions may change the values he passes to them. Which ones may be changed? In C, it's obvious: anything passed as a pointer may be changed (through the pointer), but a non-pointer is always passed as a copy, so if you don't see a * in your call site, you're safe. In C++, it's impossible to tell without further context: any parameter passed to any function is potentially subject to mutation, until you confirm that it is not in fact passed by reference, by checking the type signatures of every single function you call. Pretty irritating!

Alright, you got me. I always just personally handled it the way C does, but I suppose when you're working with other people's code (which happens a lot more outside of college) it really does sound like kind of a dick move.

JewKiller 3000
Nov 28, 2006

by Lowtax

PalmTreeFun posted:

Alright, you got me. I always just personally handled it the way C does, but I suppose when you're working with other people's code (which happens a lot more outside of college) it really does sound like kind of a dick move.

You're not alone, a lot of other C++ programmers do it that way, too. It works, it lets you do what you want (simulate pass by reference with pointers), and it's less confusing. There's a reason that most programming languages don't feature pass-by-reference semantics: while it's easy for the compiler writers to implement, most programmers don't want to use it, because it makes local reasoning about program behavior much more difficult.

So, why would anyone use references in C++, when they can just use C pointers? Two central reasons. First, C pointers are dangerous if misused. Dereferencing a NULL pointer leads to the ubiquitous segmentation fault. Pointer arithmetic that runs out of bounds can do the same, or worse yet, start overwriting unrelated parts of memory. C++ references do not have these problems. A reference can never be NULL, it must always refer to some actual value; pointer arithmetic on references is not allowed. Some C++ programmers may make a parameter pass-by-reference when they have no intention of changing the reference, but simply want a non-NULL pointer.

Second, because of the stack allocation permitted in C/C++, references can make your program run faster. Here, let's contrast with Java. All objects in Java are allocated with "new", that is, on the heap. The stack simply contains a pointer to the object. When you pass the object to some method, it's passed by value; a copy of the pointer is made, and the method parameter receives the copy, rather than simply referring to the same original pointer. Copying a pointer is no big deal, it's just one memory word. But in C/C++, you can allocate structs/objects on the stack, so that your entire (possibly really huge) object will get copied when it's passed elsewhere. Passing by reference avoids the copy. (Of course, you can also use a plain old C pointer for this, but see the above paragraph.)

:eng101:

JewKiller 3000 fucked around with this message at 04:05 on Feb 16, 2012

PalmTreeFun
Apr 25, 2010

*toot*

JewKiller 3000 posted:

:eng101:

The more you know! (thanks)

Look Around You
Jan 19, 2009

JewKiller 3000 posted:

[pointers vs references]

:eng101:

There's a lot of good points here. I haven't done much C++ programming, but I do know there's const parameters to functions and I guess I was wondering how much they're used; const correctness seems pretty hard to implement correctly but it seems like it would help things out w.r.t. passing stack allocated things. Especially because stack allocation is a huge feature in C++ that allows RAII and automatic cleanup of locals without manual memory management/garbage collection.

seiken
Feb 7, 2005

hah ha ha
I kind of agree in principle but really references are an awesome language feature and IDEs these days should totally be able to pop up a signature with the &s there for you to see as soon as you type the ( :toot:
edit: Compromise! Use const references, and pointers for mutable stuff. Either everybody wins or nobody wins depending on what your priorities are

seiken fucked around with this message at 05:01 on Feb 16, 2012

Presto
Nov 22, 2002

Keep calm and Harry on.

seiken posted:

I kind of agree in principle but really references are an awesome language feature and IDEs these days should totally be able to pop up a signature with the &s there for you to see as soon as you type the ( :toot:
And then one day you'll be stuck on an ssh connection into a remote box to try to fix some crucial problem and the only thing you'll have is vi. Where's your IDE God now, Buster? :colbert:

(I don't like references.)

seiken
Feb 7, 2005

hah ha ha
Yeah that's why I kind of agree in principle.

Plorkyeran
Mar 22, 2007

To Escape The Shackles Of The Old Forums, We Must Reject The Tribal Negativity He Endorsed
The main reason for non-const references to exist in C++ is for chaining overloaded operators. Simply returning a pointer wouldn't work due to that pointer arithmetic is a thing.

Malloc Voidstar
May 7, 2007

Fuck the cowboys. Unf. Fuck em hard.

Sedro posted:

Java has strange auto-(un)boxing rules.
that's why you never use Integers or the other boxing classes if you can't help it
and also never use things written by idiots who return null Integers

Sedro posted:

Java performs this implicit conversion that could fail with an exception, without even raising a compiler warning.
Eclipse warns me :colbert:

GROVER CURES HOUSE
Aug 26, 2007

Go on...

Aleksei Vasiliev posted:

Eclipse warns me :colbert:

Sanity is a small price to pay for that luxury.

ToxicFrog
Apr 26, 2008


JewKiller 3000 posted:

No. [...] Use of the term to mean something ostensibly similar, but actually with very important differences, is absolutely a horror; not only is it wrong, but the wrongness is masked by an explanation that sounds plausible to non-experts, encouraging them to also be wrong.

I don't understand why you start with "no" when you're agreeing with me. :confused:

JewKiller 3000
Nov 28, 2006

by Lowtax

ToxicFrog posted:

I don't understand why you start with "no" when you're agreeing with me. :confused:

Sorry, I misread your post, because apparently I'm completely retarded!

Beef
Jul 26, 2004
To go back on the reference/pointer thing in C/C++, just do whatever is semantically closest to what you are trying to achieve. For the love of god I will punch you if you pass everything around in C++ by reference because 'it makes it go faster'. I've seen people pass integers around using that reasoning...

Compilers are smart enough these days to figure out for themselves if objects really need to be copied or not. Unless you're working on some obscure microcontroller that is.

hobbesmaster
Jan 28, 2008

Beef posted:

For the love of god I will punch you if you pass everything around in C++ by reference because 'it makes it go faster'. I've seen people pass integers around using that reasoning...

I wonder if we can get ABET to require a semester worth of writing "Premature optimization is the root of all evil" on a chalkboard for all CS and engineering BS's.

Might throw Amdahl's law in there too...

New Yorp New Yorp
Jul 18, 2003

Only in Kenya.
Pillbug

Aleksei Vasiliev posted:

that's why you never use Integers or the other boxing classes if you can't help it
and also never use things written by idiots who return null Integers
Eclipse warns me :colbert:

C# has nullable value types, but you have to explicitly specify that they're nullable. It's useful for, say, databases, where you could end up with a NULL integer coming back.

Zombywuf
Mar 29, 2008

So, apparently this thread hates functions that mutate their arguments.

lol

And I really mean that, I did lol.

Cocoa Crispies
Jul 20, 2001

Vehicular Manslaughter!

Pillbug

Zombywuf posted:

So, apparently this thread hates functions that mutate their arguments.

lol

And I really mean that, I did lol.

I hate mutation, and usually find myself writing Ruby similar to how I write Erlang: lots of non-mutative transformations to old objects into new variables. I'm pretty sure it absolutely chews up heap space and adds more to each GC load, but it also keeps me sane, reduces side effects, and makes it easier to test.

Carthag Tuek
Oct 15, 2005

Tider skal komme,
tider skal henrulle,
slægt skal følge slægters gang



Immutable types rule.

trex eaterofcadrs
Jun 17, 2005
My lack of understanding is only exceeded by my lack of concern.

BonzoESC posted:

I hate mutation, and usually find myself writing Ruby similar to how I write Erlang: lots of non-mutative transformations to old objects into new variables. I'm pretty sure it absolutely chews up heap space and adds more to each GC load, but it also keeps me sane, reduces side effects, and makes it easier to test.

That's what eden space is for, use it until it profiles poorly.

Janitor Prime
Jan 22, 2004

PC LOAD LETTER

What da fuck does that mean

Fun Shoe

Ithaqua posted:

C# has nullable value types, but you have to explicitly specify that they're nullable. It's useful for, say, databases, where you could end up with a NULL integer coming back.

Ding ding ding. This is why Null Integers are useful.

Look Around You
Jan 19, 2009

Zombywuf posted:

So, apparently this thread hates functions that mutate their arguments.

lol

And I really mean that, I did lol.

I don't hate it but I like knowing whether or not calling a function will change it's arguments. That's the big thing about it for me.

The worst part about this in Java is that since all object arguments to functions are passed via a copy of it's reference and there's absolutely no way to specify const-ness you have no idea what the gently caress that function does to your poo poo half the time if you didn't write it. Also a lot of people writing Java think that AnObject x = new AnObject(); AnObject y = x; means that y gets a copy of the object x instead of becoming a copy of the reference to x which is pretty bad too.

e:

MEAT TREAT posted:

Ding ding ding. This is why Null Integers are useful.

I agree that they're useful sometimes, but not by default.

Sedro
Dec 31, 2008

Look Around You posted:

I don't hate it but I like knowing whether or not calling a function will change it's arguments. That's the big thing about it for me.
In C++ you can declare arguments as references and change their values. There is nothing like this in Java. Everything is passed by value, including references. In C# you can pass by reference but you have to be explicit in the callee and caller.

I guess you're asking for a way to make a mutable object immutable. If you pass a java.util.Date to a method, that method can mutate the date. That's the contract provided by Date, who are you to say otherwise? C++ behaves the same way in this regard.

Look Around You
Jan 19, 2009

Sedro posted:

In C++ you can declare arguments as references and change their values. There is nothing like this in Java. Everything is passed by value, including references. In C# you can pass by reference but you have to be explicit in the callee and caller.

I guess you're asking for a way to make a mutable object immutable. If you pass a java.util.Date to a method, that method can mutate the date. That's the contract provided by Date, who are you to say otherwise? C++ behaves the same way in this regard.

That's the contract provided by everything in Java, which is my problem. I am actually asking for a way to make a mutable object immutable, at least as an argument to another function. I also know full well that object references in Java are passed by value (and I even said so in my post), the problem is that you can mutate through those references and there's no way to tell if your thing is being mutated by that function or not.

e:
Ideally I'd like there to be something similar to the const functions in C++ is what I'm saying I guess, where you can tell that the function isn't going to mutate the object through the reference passed to it.

Janitor Prime
Jan 22, 2004

PC LOAD LETTER

What da fuck does that mean

Fun Shoe
Wait so in C++ you can pass a function a reference and then not be able to mutate it's field through that reference?

haveblue
Aug 15, 2005



Toilet Rascal

MEAT TREAT posted:

Wait so in C++ you can pass a function a reference and then not be able to mutate it's field through that reference?

Yes, you can use the const keyword to make the compiler enforce that.

Look Around You
Jan 19, 2009

MEAT TREAT posted:

Wait so in C++ you can pass a function a reference and then not be able to mutate it's field through that reference?

Yeah, there's const pointers/references and const methods that are actually enforced at compile time. Your program will actually fail to compile if you violate const-correctness.

e: beaten

Basically if your function is passed a const reference/pointer and you try to change the referenced/pointed to object, you get a compile-time error. There's const methods in classes that are labeled as such so that you can invoke them on const references/pointers. These are pretty much the only methods you can invoke on such a parameter to your function, so you know there's nothing changing.

Look Around You fucked around with this message at 18:48 on Feb 16, 2012

SavageMessiah
Jan 28, 2009

Emotionally drained and spookified

Toilet Rascal
So I've been asked to evaluate the feasability of porting one our parent company's java applications to the netbeans platform. The code base is just one series of horrors after another.

It's full of this construct:
code:
Thing t = new Thing();
if(t == null) {
  throw new OutOfMemoryException("some unhelpful error message");
}
Also these
code:
try
{
.....
}

//exception handler
catch(Throwable ex)
{
  ex.printStackTrace();
  return null;
}
Yes, the catch block is consistently 2 lines down from the try. Also not that the code in the .... almost never throws any checked exceptions.

Primitives are often (but inconsistently of course) explicitly boxed for no particular reason. And checked to see if they are null.

These are just scratching the surface. If any of our developers have to do this port, even the worst of them will scratch their eyes out, screaming.

Plorkyeran
Mar 22, 2007

To Escape The Shackles Of The Old Forums, We Must Reject The Tribal Negativity He Endorsed
const in C++ is sort of a big ball of mud and behaves fairly unintuitively at times, but I still miss it every other statically typed language I use.

feedmegin
Jul 30, 2008

haveblue posted:

Yes, you can use the const keyword to make the compiler enforce that.

But the function can use const_cast to make it modifiable again. It's basically silly to try and 'force' a C++ library not to do $thingyoudontlike like this. Trust the library not to do something you dislike, or write a new library.

Eggnogium
Jun 1, 2010

Never give an inch! Hnnnghhhhhh!

Look Around You posted:

Also a lot of people writing Java think that AnObject x = new AnObject(); AnObject y = x; means that y gets a copy of the object x instead of becoming a copy of the reference to x which is pretty bad too.

I have a hard time believing that. First-year CS students sure, but if you have this misconception out in the real world you're basically guaranteed to write horribly, horribly broken code unless you're exclusively consuming immutable types.

ToxicFrog
Apr 26, 2008


Eggnogium posted:

...if you have this misconception out in the real world you're basically guaranteed to write horribly, horribly broken code...

You are aware which thread this is, yes?

ctz
Feb 6, 2003

JewKiller 3000 posted:

Dereferencing a NULL pointer leads to the ubiquitous segmentation fault.

No it doesn't. The behaviour is undefined.

haveblue posted:

Yes, you can use the const keyword to make the compiler enforce that.

No you can't. See mutable.

Plorkyeran
Mar 22, 2007

To Escape The Shackles Of The Old Forums, We Must Reject The Tribal Negativity He Endorsed

feedmegin posted:

But the function can use const_cast to make it modifiable again. It's basically silly to try and 'force' a C++ library not to do $thingyoudontlike like this. Trust the library not to do something you dislike, or write a new library.

the point of const (or type systems in general) is not to make it safe to call actively malicious code

Malloc Voidstar
May 7, 2007

Fuck the cowboys. Unf. Fuck em hard.

Eggnogium posted:

I have a hard time believing that. First-year CS students sure, but if you have this misconception out in the real world you're basically guaranteed to write horribly, horribly broken code unless you're exclusively consuming immutable types.
https://code.google.com/p/java-image-scaling/source/browse/trunk/src/main/java/com/mortennobel/imagescaling/ResampleOp.java#140
e:
code:
        workPixels = null; // free memory

Malloc Voidstar fucked around with this message at 23:33 on Feb 16, 2012

PraxxisParadoX
Jan 24, 2004
bittah.com
Pillbug
php:
<?
    $a = "sock" . posix_getpid();
    $socket = "$a";
    $$a = $sock;
...
    socket_write($$socket, $msg, strlen($msg));
?>
From a "server". It's not the worst code in the "server" either.

Plorkyeran
Mar 22, 2007

To Escape The Shackles Of The Old Forums, We Must Reject The Tribal Negativity He Endorsed

Beef posted:

Compilers are smart enough these days to figure out for themselves if objects really need to be copied or not.
With user-defined copy constructors they really aren't.

Stepping through code in a debugger is also way less annoying when things pass around const references rather than values.

JewKiller 3000
Nov 28, 2006

by Lowtax

ctz posted:

No it doesn't. The behaviour is undefined.

Good point, you're correct. I was being careless.

Adbot
ADBOT LOVES YOU

Hammerite
Mar 9, 2007

And you don't remember what I said here, either, but it was pompous and stupid.
Jade Ear Joe

PraxxisParadoX posted:

php:
<?
    $a = "sock" . posix_getpid();
    $socket = "$a";
    $$a = $sock;
...
    socket_write($$socket, $msg, strlen($msg));
?>
From a "server". It's not the worst code in the "server" either.

Are those the only lines that make use of the variables $a, $socket, and [the symbol that gets defined by the $$a = ... on the third line]? What kind of tortured logic do you have to engage in to conclude that all of that is needed or desirable rather than just writing

socket_write($sock, $msg, strlen($msg));

  • 1
  • 2
  • 3
  • 4
  • 5
  • Post
  • Reply