6 ms·
Funnily enough, when I joined a C++ team about 4 years ago I could never get any senior dev to move away from using references instead of const pointers. Refer
by lelanthran 3y ago
Funnily enough, when I joined a C++ team about 4 years ago I could never get any senior dev to move away from using references instead of const pointers.
Reference parameters are awful; the reader has no idea whether the argument will be modified or not without reading the header file.
With const pointers you never have this problem.
- pjmlp 3y agoI do a mouse over and move on. Hardly any different from "var" parameters in plenty of languages since the 1960's.
- shadowgovt 3y agoIt's cool that you're using development tools that successfully parse the C++ you're working on. I found that to be a rare circumstance in any complicated code base. And once you lose that capacity, oh boy does this language become terrible fast.
- fsloth 3y agoI think you need to define what is a complicated code base here. Visual Studio works fine for millions of lines but I am sure the difference in experience can vary wildly.
- shadowgovt 3y agoVisual Studio crashes on the code base I maintain. It's a monorepo using bazel to manage it, and between the sheer number of includes compilation units take, the hundred thousand plus compilation units themselves, and some decisions made early on that are hostile to VS code tooling because the original developers didn't use VS code (such as hiding template implementations in .inl files that are included in the corresponding .hh file), VS code is functionally unusable for us. In general, the company moves forward because most of the same people who established the code base are still working here and they just already know all the quirks and can Intuit argument types, often because they wrote all the classes in question.
- fsloth 3y agoOuch, my condolences.
- ftrobro 3y agoVisual Studio != VS Code. I've always found Visual Studio to be great at C++ so I'm interested in knowing which of the two you meant?
- shadowgovt 3y agoVSCode, to be clear. The fact that Microsoft released two products in the same domain with almost the same name consistently trips me up. No, we don't spend money on code editors around here; I meant VSCode.
- TillE 3y agoVisual Studio Community is free to any company whose annual revenue is under $1 million USD. It's fully functional, unlike the ancient Express versions.
- fsloth 3y ago"No, we don't spend money on code editors around here; I meant VSCode." Not spending money in tools sounds like a very strange economics for software development. If interviewing does not scare you I warmly suggest finding a new employer.
- CyberDildonics 3y agoVisual Studio is not visual studio code. Also if you have a hundred thousand compilation units, it might be time for some shared libraries instead of one monolithic program.
- shadowgovt 3y agoOh I completely agree, but I am a mere senior software engineer and I have not yet figured out how to chisel past the corporate cruft of the three folks in charge of the codebase who believe monorepos are right because Google is doing it, therefore it must be the best way to do things. Nevermind that I have some experience with how Google did it, and it turns out there's a lot of ills you can solve with a 25,000+-strong engineering force that you can't in a smaller org. VSCode at Google never worked for me either, but punching a novel symbol into company-wide syntax-intelligent internal code search and glancing at the first response, which was likely to be the right one because it was a Google search engine so had well-tuned signals for "things humans care about," always did. They're not interested in how Google does it, merely that they do it so you can't get fired for making an architectural decision that worked for Google. Nor are they really interested in solving the tooling issue because it works for them; they just grep-and-pray. They're very fast at it because it's all they know so they've gotten quite good at it (when they have to do it at all; often they just know the types because they wrote the classes. ;) ).
- pjmlp 3y agoVS, QtCreator, Android Studio, KDevelop, C++ Builder,...are some of the names that come to mind where this herculean task is possible.
- shadowgovt 3y agoAnd they are, indeed, very impressive. But the nature of the language makes their task extremely difficult, and in my experience they aren't reliable. Besides the issue of C++ being just hard to compile (global symbol mutation via the macro system, the way templates instantiate, the compilation unit as the fundamental element of compilation meaning any individual compilation unit can require hundreds to thousands of include files as input), the language is rife with undefined behavior and assistive tooling is allowed to crash on undefined behavior. So, yes, if your tooling crashes it may indicate a problem with your code---but how are you going to find it now that your tooling has crashed? We've had a couple of initiatives at my organization to try and get tooling operational across the code base. They haven't stuck. Developers keep having to fall back to grep and pray. I prefer working with languages where there are simply fewer features and less undefined behavior. It makes the tooling more reliable.
- pjmlp 3y agoFrom other comments, it doesn't seem the organisation is willing to adopt the right tools, naturally one gets what one doesn't pay for.
- shadowgovt 3y agoIndeed, although I don't know what we could throw money at that would fix the problem of "Clangd crashes trying to provide LSP services for this codebase." We could buy Visual Studio and roll the dice and hope that it's more robust than vscode, but I have no particular reason to believe it would be. This organization has its work to do. My advice to other teams starting out is "C++ may be cheap in terms of hiring people and libraries that exist, but consider the cost once your codebase gets large. This is not a language that lends itself to safe behavior or tool-comprehensibility, and if that's something your project needs, be prepared for that. Other languages are safer, other languages are simpler for tooling to digest."
- fluoridation 3y agoI recently worked in a fairly large Rust project that I could simply not load into VS Code. rust-analyze would allocate more and more memory until it eventually crashed. I have never seen that with C++ code, besides that time I was investigating how someone was using CImg and found out that the CImg developers thought it was cute to make a single 3 MB header, and that brought the debugger to its knees. It still didn't crash, though! So yeah, difficult-to-parse codebases are not an exclusive feature of C++.
- shadowgovt 3y agoInteresting. This is the first I've heard of a Rust codebase too big to parse, but I'm not deeply surprised; Rust tooling hasn't been hammered on for as many decades as the C++ tooling. I'm medium-level confident there's meat on the bones of optimizing it to a point better than the C++ tools because they made choices in the language that do some amount of compartmentalization, so you don't get that "one #define up in this header you've never seen changes the meaning of symbols in every other file in this compilation unit." Unless that is possible and I simply haven't gotten deep enough into Rust to realize it yet.
- fluoridation 3y agoFunny you should mention that. I'm pretty sure the reason this project was so difficult to process was the (IMO) abusive use of macros. I'm talking foo!( in one line, and several hundred lines below was the closing parenthesis.
- shadowgovt 3y agoMacros (and in C++, their neighbor templates, since both are ways to make conditional decisions about what code to generate evaluated at compile time) are definitely the way to test out the limits of the compiler's performance. I haven't done enough Rust yet to hit this, but I don't doubt it happens. I did once make vscode scream on a very intricate family of conditional TypeScript types... Code compiled fine, but the editor started to take dozens of seconds to determine on-the-fly if types were sound. Back in the day, I once worked with a C++ game engine where the developer was obsessed with interfaces vs. implementation. Every class, even if there was one implementation, had an abstract interface wrapper. It was the first codebase I ever encountered where the compiler (on my Mac laptop) choked on it because it ran out of RAM trying to compile it.
- nly 3y agoUse a decent IDE. Most render & at the call site so you know. I find this all a bit rich anyway. In languages like C#, everything is a bloody reference and this lame concept of "reference types" corrupts developer minds.
- pjmlp 3y agoJava or Python would have been a better example, as that isn't the case with C#.
- raincole 3y agoI'm pretty sure one of the biggest differences between C# and Java is that in C# you can't assume everything is a reference. A strict is passed by value.
- fluoridation 3y agoNo, strings are passed by reference, it's just that the string type is immutable. Passing a string to a function doesn't create a copy, but there's also no way for the callee to modify the object that the caller points to. It is true that C# has value types that are by default passed by copy, though.
- raincole 3y agoI mistyped struct as strict.
- lelanthran 3y ago> Use a decent IDE. When I'm navigating code, the references aren't a problem, because I am using an IDE of some sort, usually. The complaint I made was about reading, not navigating, for example when reviewing a PR.
- uxp8u61q 3y agoUse a decent IDE that allows you to review PRs from within the IDE.
- ant6n 3y agoCant u use a const reference?
- dureuill 3y agowith const pointers you have the different problem that you need to define what happens when the nullptr is passed. While I would certainly prefer the reference to be visible at the call site (a mistake Rust did not repeat), if I have to choose, I prefer the inconvenience of having to use an IDE like qtcreator that will display references in a different style, to introducing an invalid value that needs to be handled (and will be mishandled). So yeah, as a senior dev, it checks out.
- TonyTrapp 3y agoHow does a const pointer express this in a way a const reference can't?
- dtho 3y agoIn the absence of IDE features, you can't differentiate between value arguments and reference arguments unless you view the callee's prototype. Pointers do not have this problem.
- TonyTrapp 3y agoIn the absence of IDE features, you also can't differentiate between a function taking a pointer and a const pointer. You must be aware in all cases that the value that you pass to the function may be modified. Yes, the function would not be modifying the pointer itself, but the outcome is exactly the same. A reference is pretty much equal to a non-nullable pointer in this context.
- lelanthran 3y ago> In the absence of IDE features, you also can't differentiate between a function taking a pointer and a const pointer. So? It still helps me with decoding `foo(bar, baz)`, as without the `&` I KNOW that bar and baz would not change after the call. And since both bar and baz are in the local scope, I already know whether they are pointers or not. With pointers, all the information necessary to determine if bar and baz would change after a call to foo is in the local scope. With references that information is elsewhere.
- gumby 3y agoA pointer can be nullptr while a reference cannot so that would be a step backwards. Also the “problem” you describe is not solved by your proposed “solution”. A const pointer can point to something that can be modified. You can declare a pointer to a const object, or, you know, declare a const ref.
- shortrounddev2 3y agoMicrosoft created SAL so you can annotate pointers to instruct the compiler to put up warnings or even errors for null required fields: _Success_(return) //out parameters should be set if this returns true bool tryGetValue( _In_ Map const* map, //pointer is for input only and cannot be null _In_ char const* name, _Out_opt_ Data* value //pointer is for output and can be null ); If you pass null for _In_ params, the compiler will warn or error. You return true without setting the _out_opt_ parameters, the compiler will warn or error. You can pass null to _out_opt_, and the compiler will warn or error if the function body doesn't properly check if the parameter is null
- fluoridation 3y agoOf course, that only works if you're passing a literal null. If you're passing a variable the compiler will not check anything, so this doesn't really solve the problem.
- jprete 3y agoThe annotation does need to be propagated backwards to callers and declarers - and there needs to be a way to "annotate" an existing pointer in the scopes where you've proven that it's not null - but that's better than having no annotation at all. (Although this is something I'd 100% want C++ to do, and not with an annotation but with a very short operator or reserved word.)
- lelanthran 3y ago[EDIT: Brainfarted in the last paragraph, read "const ref" as "ref"] > A pointer can be nullptr while a reference cannot so that would be a step backwards. Backwards from what? A reference can't be null, but it can still be invalid, which is a more common problem than forgetting to check for null-ness. > You can declare a pointer to a const object, Yes. I should have said that instead. > , or, you know, declare a const ref. That doesn't solve the original problem with references, though. I hate reading `foo (bar, baz)` and having to dig into the header to find out that bar or baz or both might be modified after the call to foo. When reading code, I want to be able to skip over anything that does not modify the state of variables in the current scope. Using references means that I have to know what every single call does. Using pointers exclusively, I can simply skip calls to functions with arguments that aren't pointers.
- MereInterest 3y agoWith const pointers, you have no idea if the parameter is implicitly optional, if it must point to a valid object, if it will throw an error when provided with a null pointer, if it will segfault when provided with a null pointer. Not even reading the header file will help you here. With const references you never have this problem.
- alexvitkov 3y agoYes, but non-const references are utter trash since you can't tell you're passing a mutable reference when looking at the call site, so for the non-const I'll always pass by pointer. Const references are less offensive, but I'm not going to pass non-const by pointer and const by reference, that's just inconsistent for no reason. If null is not a valid value, throw an assert at the beginning of the function. It's not like references can't be in a broken state, they're just syntax sugar for pointers (that also happens to wildly complicate the language's type system)
- ninkendo 3y ago> Const references are less offensive, but I'm not going to pass non-const by pointer and const by reference, that's just inconsistent for no reason. Why use pointers at all? Just use const references for immutable stuff, regular references when you want mutation, normal values when you want copy semantics, and smart pointers for other cases (unique_ptr for move semantics, shared_ptr for lack of clear ownership, etc.) If you want to represent nullability, std::optional is a good choice. > If null is not a valid value, throw an assert at the beginning of the function Yikes. This means the compiler will not catch it for you. Why make this a runtime issue? Use the type system to your advantage.
- alexvitkov 3y agoIf references were guarenteed sane and consistent values like in Rust, sure - but it's trivial to get a bogus reference in C++, so I don't buy the type safety thing. An assert actually catches errors, a reference just declares intent. As for smart pointers there's a lot of domains with tight performance requirements where you can't afford them - and to be quite frank, if you can afford to use shared_ptr you can also afford GC, so just use a sane language
- ninepoints 3y agoIMO read the damn header file and abide by the api contract. A const pointer type suggests nullability, and possibly even pointer arithmetic is permissible.
- fsloth 3y ago"get any senior dev to move away from using references instead of const pointers." ... "the reader has no idea whether the argument will be modified or not without reading the header file." It sounds like the problem is not using an IDE. Use references whenever posssible. Then you don't need to do a null pointer check. C++ is a footgun. And like with all guns, security first. With guns - put the safety on. With C++ - check the pointers are not null. OFC one can argue that with proper instrumentation invalid pointers are captured sooner than later, but the fact is it's much easier to represent invalid program state using pointer than references.
- thecodedmessage 3y agoYes, the "C++ is not usable on its own and needs other tools" defence of C++ :-)
- PaulDavisThe1st 3y agoIn my experience (31 years of C++) it is much more likely that problematic pointers will be non-null but also invalid.
- gpderetta 3y agoIf you pass a pointer (or anything with reference semantics) by value you can still get non local mutation through it without obvious call site syntax. There is no perfect solution. Avoid out parameters if possible, otherwise make the semantics clear via function naming or at least parameter naming conventions.
- YesBox 3y agoI use this solution as a solo dev: #define $ And add the $ in front of all non-const pass by reference parameters in the call