Pointers

When exactly do people use them in C++ outside of interacting with legacy C stuff? I find myself at a loss as to when I usually need them. Most of the situations in C where they'd be used don't seem to exist in C++.

Attached: cpp_logo[1].png (918x1032, 45K)

Other urls found in this thread:

invidio.us/latest_version?id=xnqTKD8uD64&itag=22
gist.github.com/cirocosta/e61e52cc6afe2633500b
queue.acm.org/detail.cfm?id=3212479
twitter.com/SFWRedditVideos

Memory management.

Out and In/Out parameters, allocating memory, in most data structures, runtime polymorphism, function pointers.

When your function requires handle to an object, of course. Pointers are simple and reliable, you take an object by the leash and use it how you want. No abstractions or workarounds.
Smart pointers are for lifetime ownerships, you can and should let functions or data structures that do not modify the object's lifetime, point to it with a bare pointer. It makes your syntax simple and eliminates conflicting situations like copying shared_ptr or referencing it. Etc.

Here watch this for a few minutes @ 12:10
invidio.us/latest_version?id=xnqTKD8uD64&itag=22

Rarely, references and unique or shared pointers are usually preferable.
The primary usage for bare pointers is when you really need to pass an address around, for example to some memory allocated on the heap. Many containers provide a methods which return pointers to directly access their underlying storage because it is sometimes more convenient than using an iterator.

I think its better style to just return a std::tuple or std::optional than use in/out pointers in C++.

OP here. I don't remember the situation, but I did use make_shared for a smart pointer, but that was a one time thing. I'm still not sure what exactly a pointer generally better over a normal variable.

Optional reseatable references.

What kind of retard passes copies of data into functions? Just pass the pointer, it's faster and uses less memory.

>invidio.us/latest_version?id=xnqTKD8uD64&itag=22
got more of them cool links?

You definitely should not be using out parameters in C++

A pointer is just a variable for holding an address. shared and unique pointers are for managing ownership of a heap allocated object more sanely.

>pointers
>leash
hahahaha

Good luck having shared resources without pointers.

I usually just use &.

make_shared is a waste of instructions in modern C++ since templates now correctly deduce the type.
>over a normal variable.
I don't understand. Pointers are normal variables you use to access other normal variables. They're mainly used in the special case that you access an object that lives somewhere and you don't care where - heap, stack, static segment, etc. If you want to know why heap allocations are better than stack allocations, it's a different topic.
Well the entirety of cppcons are a good start. Invidious just grabs videos off youtube so you can find them there if you need that GUI.

You still should be using make_shared, idiot.
Lack of type deduction was not why make_shared was added. make_shared is actually more efficient as it allocates the object and control block on one go.

This. But it's still a polymorphic object with virtual functions so it's still inefficient. The C++ spec is fucking busted.

That used to be the case 10 years ago. Consult your standard library implementation or debug it yourself to see the difference in c++17. You only need make_* to specify the template typename.

C++ is shit, write in C89 only.

C89 code looks and performs like garbage, C++ provides a more wholesome non-hair pulling experience.

>Just pass the pointer
Yup, that's a great one-size-fits-all solution. Don't ever do anything else.

It looks beautiful and performs faster than your object filled shit, and if you think otherwise then you're a CIA nigger shill.

Enjoy your memory leaks.

>beautiful
>performs faster
This is 5 lines in C++.
gist.github.com/cirocosta/e61e52cc6afe2633500b
Oh and glib's hashtable is trash and unsafe compared to std::unordered_map which has standards to live up to.

From the talk. Use pointers folks.

Attached: scrot.png (879x505, 230K)

>no move semantics
>no copy elision guarantees
>no constexpr
it's slow trash

>he lets the programming language write the code for him
Enjoy your CIA backdoored libraries faggot.

>he writes his own static, unaudited, buggy, slow, easily-exploitable code and turns off OS security features to compensate
Yeah okay schizo

>he willingly takes the CIA glowing nigger cock into his little tight twink codebase
look at you, you sick fuck

>he is a dumb ugly chubby schizo who writes code Ken Thompson would vomit over
Show me your github

>assuming I let microsoft contractually and legally rob me of my god tier code because I use their GLOWING nigger web repos
nice try CIA NIGGER, I'm not giving myself up that easy you fucker

>he doesn't write code that generates code for him
pleb

Pathetic arguments

>imagine cucking yourself from the pleasure of writing your own glorious code
I bet you use gcc, nigger.

If you give me your code and my mere self can crack it, that means my employers can crack it as well. This reality check will show you how vulnerable you really are.

I doubt it, glow nigger.
You probably just want to steal my god code and sell it to microshaft, well it ain't happening.

Option A:
>you are a great programmer, microsoft pays you $300k/yr for your code, and for schizophrenia treatment, hires a qt caretaker and bodyguards
Option B:
>your code is trash, you are so insecure of other people, you hide deeper, beyond anonymity, into a sad closed-curtain lifestyle, and die of stroke at age 30 due to self-induced stress

Fuck you CIA nigger, I choose B so I don't become brainwashed by microniggers to hand them over my precious C89 code in exchange for useless money, it's a sin to be greedy, CIA nigger.

You fell to temptation and chose at the Devil's will, a path of life against God, one of sin, self-hate and cowardice. He who hates another man or himself, hates God, as all humans are created in God's image. You signed your pact with Satan and will be offered no help, no condolence, and peace of mind. When they come, remember these words.

If you don't see where they're needed you're still low/medium skilled
I use pointers more than managed memory ...in C#

Stop being faggot catholic nigger.

When you go against the natural order, nature will come for you with its guardians. Are you getting enough sleep? Does food even taste good anymore? Do your eyes deceive you sometimes (what you see is real for a few glimpses)? They're always there, you know. Terrence Davis knew they were clawed to his back all the time, running up and down, so layed on the tracks to kill them. They always get their way to restore order and love in the world.

reference is just a syntactic sugar for "*const"

Oops, no it's not. References can't be initialised NULL and aliases of objects in the same stack frame take no memory.

>References can't be initialised NULL

int& nullref = *(static_cast( NULL ));

(will throw warning but it works)

Invokes undefined behaviour.

That's UB in the best case, nullpointer deref exception in worst case.

>but it works
No, it's UB you fucking idiot.

>That's UB in the best case, nullpointer deref exception in worst case.
Literally the other way around you fucking idiot.

I'd rather my apps not crash. I'd like to save my work and restart when I see weird symbols or colors pop up somewhere.

you said you can't but I did

>muh UB

cope harder referencefags, maybe you should go back to your rustmommy she will make sure you can't write such code

Attached: 1566562615785.jpg (600x800, 218K)

People like you should have a restraining order of 5km from any computer.
Please for the love of god, never program again.

>but I did
No you didn't. You invoked UB.

I would MUCH rather my program crash than corrupt or read arbitrary memory.
That is far, far, FAR worse than crashing.

Attached: images.jpg (212x205, 8K)

Then keep it on your system, and never upgrade either.

>I don't understand C++

You didn't, what you wrote isn't C++ code because it cannot be defined by any ISO C++ standard. Undefined behaviour means the compiler has the freedom to replace that line with abort(-1); she so chooses.

When you care about performance, because shit like
class my_shitty_oop {
some_data x;
...
void transform() {
whatever
}
}
...
for (auto &o : my_shitty_object_collection) {
o.transform();
}

will completely kill your d$, unlike
struct my_shitty_obj {
some_data x;
}
void transform_my_shitty_objects(my_shitty_obj* os, size_t n) {
for (size_t i = 0; i < n; i++) {
whatever
}
}

are you fucking retarded? These have the same memory layout and performance characteristics you massive retard

Great so now your app's forums are full of angry consumers, you refund them all, and go out of business, and nobody buys anything from you ever again.

This.
You just don't understand how C++ gets turned to machine code.

These generate the same code, in fact the top could possibly be slightly more efficient because of the iterator.

>program loudly crashes
>user sends in bug report
>bug is fixed
>user experience improves
>product quality improves

>program silently reads/writes to arbitrary memory
>program doesn't crash
>down the line, some weird bug occurs as a result and crashes (might not even do that)
>user sends a bug report
>devs can't fix it because they have no idea what the root cause is or how to reproduce it
>bug continues to affect users
>user experience degrades
>program quality degrades

summerfags please leave

Definitely sound better than the alternative.

i use them for classes I can't be fucked making move/copy constructors for, but need in a vector.

I'm not sending any reports, it's okay for me that a program goes funny sometimes, it;s just computer stuff. I do however become furious when my program crashes in the middle of work.
And let's be honest, if developers write UB, then they can't fix UB, probably.

You forgot the worst case
>Silently corrupts memory
>Never causes a crash, but instead alters behavior in a way that isn't immediately noticeable
>Users filesystem is now corrupt, losing all their files
>And it's all your fault
This actually happened in the Linux kernel recently.

>I'm not sending any reports
>STOP LETTING MY PROGRAM CRASH DAMMIT
>NO I WON'T TELL YOU WHAT CAUSES IT TO CRASH
You are part of the problem.

>it's okay for me that a program goes funny sometimes
So it's okay if UB causes your program to corrupt files?

Dude I paid money for a product. What, those guys can't pay some indians to fuck around in VMs?
>corrupt files
That's why I press CTRL+S 2/3 times.

>That's why I press CTRL+S 2/3 times.
You can't be serious. Do you actually think this solves anything?

While I agree that companies should indeed have some kind of quality assurance instead of being cheap fucks, you're not helping yourself by not giving them the information they need to fix bugs, and deliberately withholding that info from them isn't gonna make them change their minds.

>t. retards
x is the only relevant data for the transform function
your shitty object class always contains irrelevant data which clutters d$ (denoted as first ...)
a struct containing just the data it needs for a transform maximizes d$ utilization
i should have named the struct tranaform_data so even brainlets could understand, but whatever
and vectors or any other dynamic shit you write is _never_ better than a plain array, never (it can at best be the same on average)

an std::vector and plain array are exactly equal in iteration performance.
If class my_shitty_oop contains a field then why the fuck wouldn't struct my_shitty_obj contain it too?
You're a fucking idiot.

I think he's talking about data oriented design but that's orthogonal to OOP/procedural, you can still get shitty memory layouts with procedural code

>contains irrelevant data
If it's in the same class, then it is relevant data. If your struct does not contain this relevant data, it is an incorrect implementation. Or are you trying to sneak in AoS vs SoA? You can do the same in C++.
>_never_
std::vector has a ton of type specifiers slapped on and invariants to take advantage of. Your C code assumes a pessimistic point of view, that elements can overlap, that 'whatever' can change 'n' so it cannot apply loop unroll, etc.
I can modify my own nonstd::vector as a full replacement which has __restrict, compile-time iterators, etc, and will outperform your shitty loop. All with the same syntax of std::vector.
Much of the same reason is why Fortran gladly outperforms C in a lot of cases.

>muhhhhhh cache
Dude there is no such thing as cache in the C++ standard. It's an abstract language with an ordered, flat, contiguous address space. If you're thinking of cache, you're using the wrong language.

One of the major reasons to use C or C++ is that your data will map predictably and flexibly to the memory layout of the underlying machine. C++ will even expose some cache parameters with std::hardware_destructive_interference_size and std::hardware_constructive_interference_size. If you're not thinking of cache you're writing the wrong language.

I know he is but I don't think even he knows what he's talking about.

>hurr durr what are references

>will map predictably and flexibly
It won't. CPU engineers spend thousands of manhours developing this dreadful, slow, buggy abstraction layer just so we, for some stupid reason, support the idea of a linear address space. Without that layer, if C was truly abstract assembly, pointer dereferences would be a linked list walk, or you would have to use something like:
void* deref(void* ptr, size_t times)

C does not, in any way, reflect the presence or absense of virtual memory and memory paging. It just gives you a standard library that hides such details. If you think about caches and do not bypass the standard library, to work on non-portable code directly, you are not truly thinking of caches.

Please read:
queue.acm.org/detail.cfm?id=3212479
Now stop polluting my fucking workspace and brainwashing people.

>why the fuck wouldn't struct my_shitty_obj contain it too?
have you ever seen an oop codebase? you always have some god-object which contains whatever was convenient for the pajeet oopers and everyone inherits this object for whatever reason
a plain struct that only contains in_data and another for out_data is the only way to not murder your d$
>If it's in the same class, then it is relevant data
wrong, it's in the same class because it's needed for other functions than transform(), and only because some retard thinks it belongs there conceptually, which is a great way to kill performance
>If your struct does not contain this relevant data, it is an incorrect implementation
wrong, it is correct if it correctly implements the transform(), everything else is irrelevant
the proper way to write high-performance code is: data_in, data_out and data_transform which applies the transform over an array
>Your C code assumes a pessimistic point of view, that elements can overlap, that 'whatever' can change 'n' so it cannot apply loop unroll, etc.
restrict for first point, and wrong about second point if you're talking about C
easy fix, and very clear about what it does and how
>I can modify my own nonstd::vector
which is what everyone using modern cpp does, and it's good in teams where fresh-out-of-uni programmers work, but no, you will at best get the same perf as shitty loop pver plain array
>Fortran gladly outperforms C in a lot of cases
irrelevant here, fortran outperforms cpp too for same cases as c, no matter how hard you try
that's cool if you're webshit, but not if you're writing high-performance code
when your transforms have to be WCET analysed, you'd better make damn fucking sure you're not wasting any d$ because it makes it trivial to do WCET
wrong, even assembly is a high-level language these days which doesn't reflect much at all about the state of hardware
pointer renaming,speculative execution,...

>have you ever seen an oop codebase? you always have some god-object which contains whatever was convenient for the pajeet oopers and everyone inherits this object for whatever reason
This is an argument against abuse of OOP and shitty programmers.

>that 'whatever' can change 'n' so it cannot apply loop unroll, etc.
No.

no, it's an argument against oop because oop makes it very easy to write bad-performing code
you can't go wrong with a simple "oipeline" point of view, bonus: makes it extremely easy to see data flow for potential parallelization

>only because some retard thinks it belongs there conceptually, which is a great way to kill performance
You don't know that and you can't make such assumptions. My code doesn't. Plus, anyone can easily do the exact same composition of objects in C structs.
>implements the transform()
No, your API is completely backwards now and class relations, abstractions, encapsulations are down the drain. That is, unless you employ struct-of-arrays, which I said is incorrect, since we are examining array-of-structs.
>high-performance code
There is no such word for non-machine language. There is no tool on the planet that can statically analyse C++ code and mathematically PROVE that if you rewrite it in a spastic way, it will be faster on 100% of architectures g++ can compile to, 100% of the time.
>restrict
You did not add restrict. My vector class has it, and it is faster because it takes all data into effect.
>wrong
Do you know how compilers work or will you show me why I am wrong?
>everyone
You don't have a God's view of Earth and cannot make such statements. A lot of companies literally fork compilers and standard libraries and optimise them for their exact use-cases. It's very easy to do, much like editing your WM config file.
>at best get the same perf
I just showed you how you're wrong with your assumptions.
>no matter how hard you try
Unless I write my c++ code to use the same assumptions fortran does, then I can replicate it entirely.
>WCET
Don't know, don't care. If performance is a concern to you, pay me accordingly. I will gladly write unreadable and assumptious code.

as an optional reference to a heap allocated object

Attached: 1566431046539.gif (400x225, 975K)

>t. pajeet

There is not a single situation other than basic types where copying is faster.

Actually even passing complex types can be more efficient because it eliminates aliasing.

>std::tuple
>have to figure out return orders and their types
no thanks. I rather return a struct or use in/out param

you just refuted yoyrself.
in general if the object is smaller than a pointer and isn't being modified it's optimal to pass a copy.
otherwise pass a reference.

pointers are references that can be null, so the semantic is similar to std::optional with a different implementation.
in c++ you pretty much never need to pass an optional argument since you can just provide an overload that doesn't take that argument in the first plqce, which is also more efficient since it's compile time instead of runtime choice.

Explain to me the mathematics behind this reasoning.

It's not about mathematics, it's about optimisation.
If you have some function such as this:
void foo(Bar *b1, const Bar *b2)
{
baz(*b2);
qux(b1);
// This function might have mutated *b2 if b1 == b2, so it must be fetched from memory again
quux(*b2)
}
If you pass by value you don't get that. It's the same motivation for __restrict and pointer aliasing rules in general.

>smaller than a pointer
Even if you have a bit field, copying data is multiple small operations, not a memcpy because that would touch your padding, which is UB.
>so it must be fetched again
Where does this happen? You fetch b1 every time you deref a pointer. Or are you talking about microcode-level programming I have zero direct control over?

Just learn how to use smart pointers.
You either use unique_ptr or shared_ptr.

So if I have
unique_ptr p;
what is the best prototype of a function that gets a widget and calls a const method?

see invidio.us link:

pointer bugs caused death of thousands of lives and tens of billions of dollars of losses

>you can't make such assumptions
i've seen enough codebases to make such assumptions
>My code doesn't
doubtâ„¢
>class relations
what classes?
>abstractions
why? it's not the job of high-performance code to be abstract, that's what wrappers are for
>encapsulations
a cpu does this: take input, compute, spit output
it doesn't give a shit whether the input is a chair, or whatever, so don't fucking even think about bringing those shitty notions to high-performance code
>SoA vs AoS
irrelevant here, cpp coould have an easy SoA/AoS switch, but it's not very important, important is how you structure your code
>There is no tool on the planet that can statically analyse C++ code and mathematically PROVE that if you rewrite it in a spastic way, it will be faster on 100% of architectures g++ can compile to, 100% of the time
of course not, that's why you always need to think about the platform you're running on
that said, it's very safe to say that iterating over contiguous chunks of memory with, say 95% d$ utilization is faster than doing the same with 40% d$ utilization on every architecture currently used
>You did not add restrict
consider it done
>My vector class has it, and it is faster because it takes all data into effect
doubtâ„¢ mind showing benchmark?
>Do you know how compilers work
i know clang very well, gcc less so but still pretty well
>will you show me why I am wrong?
when i get home; why you're wrong: -funroll-all-loops is pretty aggressive
why you're wrong about unrolling: whether it improves performance depends entirely on n
>You don't have a God's view of Earth
ok autist, 70-90% of fortune500 oop codebases being performance nightmare
>much like editing your WM config file
static analysis isn't that easy, i'd know, having done my thesis on it (thread-modular analysis)
>I just showed you how you're wrong
you just made up some mythical "my vector" and said "hey it's possible to beat 4 unoptimized C lines with ~700 lines of optimized cpp templates"