Showing posts with label reference. Show all posts
Showing posts with label reference. Show all posts

Thursday, 14 September 2023

C++: I was today years old when I learned this about shared_ptr

I was on a review for a colleague and there was this piece of code which stood out to me, I could not figure out what was being achieved.  Without being specific it was essentially

static std::unique_ptr<B> Create(const std::shared_ptr<A>& referenceToA);

Just the function prototype didn't sit right with me and the use case was even more strange to my eye for the "B" structure here being created has the shared pointer in the members.

struct B
{
    B(const std::shared_ptr<A>& referenceToA)
        : mMyA(referenceToA)
    {
    }

public:
   static std::unique_ptr<B> Create(const std::shared_ptr<A>& referenceToA)
    {
        return std::unique_ptr<B>(new B(referenceToA));
    }
};

private:
    std::shared_ptr<A> mMyA;

And my head just lot it.  To my eye this API, the create function here, is given a constant reference to the shared_ptr and what can be constant about a shared_ptr?  Well the internal reference count, or so I thought.  I believed this was a mistake, I believed the compiler would throw this one out and say "No, you can't change the reference count of this const object".

Never had I ever thought that the shared_ptr is actually referencing some other controlling block elsewhere.  My understanding was therefore flawed and I'm happy to admit naive.

So what would happen here?  Well, the B constructor, actually copies the shared_ptr control block, it therefore does and can increment the reference counter to the shared_ptr.

As counter intuitive as the const is therefore.  We aren't actually saying the shared_ptr itself is constant, rather the reference to it is, we should be reading the parameter type as std::shared_ptr<A>const &  referenceToA.

I felt rather silly for not realising this earlier, not least as I did once write a C program to switch out the qualifiers on a function call to make things like this stand out in formatting my code!!

But it has slipped my mind! Okay! I'm old, shut up.

Here is the full code of what I put together to understand this: 

#include <memory>
#include <mutex>
#include <queue>
#include <string>
#include <cstdio>
struct A
{
A()
:
mIndex(GetNextIndex())
{
}
~A() = default;

const int mIndex;
private:
static int GetNextIndex()
{
static int index{ 0 };
return ++index;
}
};
struct B
{
public:
B(const std::shared_ptr<A>& parent)
: mParent(parent)
{
}
std::shared_ptr<A> mParent;
static std::unique_ptr<B> Create(std::shared_ptr<A>const &  referenceToA)
{
return std::make_unique<B>(referenceToA);
}
~B()
{
mParent.reset();
}
const int& GetParentIndex() const { return mParent->mIndex; }
};
int main()
{
std::shared_ptr<A> original{ std::make_shared<A>() };
printf("Original %i: %i\n", original->mIndex, original.use_count());
auto createdB{ B::Create(original) };
printf("Copy %i: %i\n", createdB->GetParentIndex(), createdB->mParent.use_count());
printf("Original %i: %i\n", original->mIndex, original.use_count());
}

However, I have to say, I still don't like this; clever as it is, there's a hidden copy going on, in the B constructor the copy of the shared_ptr control block and it's reference count incrementing from 1 to 2.

It does quite neatly move ownership of the pointer, but the const and the reference just make my brain spin.  So where this can only gain 10/10 plaudits for C++ smarts, it only gets a mere 3/10 on the maintainability ladder for me, and only when we have the const& together, when written as at the top of the page this drops to 1/10.

Performance is also a factor here, if we wanted better performance we would have to consider whom owns the original A here.  If no-one and it is always added into the shared member in B, well move it... Create once and move it, this code doesn't communicate that as an option, but it certainly could be.



Monday, 15 October 2018

C++: To Reference or Not

Constant Something Reference or Something constant reference... I ask myself this in a similar manner as Prince Hamlet at the start of the nunnery scene... For as a C++ programmer and English speaker I've always found myself most comfortable using the phraseology thus:

const int X (0);

And to pass this to a function:

void foo (const int& p_X);

I find this most useful, we're passing a constant integer reference to the function... However, I was recently challenged that this meant something else to a reader, her input was that it meant "constant integer" reference, that is we would ONLY be able to pass "const int" instances, not "int" instances.   The thinking being:

const int X(0);
void foo(const int& p_X);

foo(X);

Would compile, whilst:

int Y(42)
void bar (const int& p_Y);

bar (Y);

Would fail to compile or at least spit out a warning because "int" was not able to be passed into the function as "constant integer" and "integer" to this reader were different types.

They're not really of course, constant is a decorator (and one which we can remove with const_cast) the aim of using "const int reference" as the type is not all of our purpose in declaring the function like so, the purpose is to communicate what we do with the value going into the function.

It is 100% not about stopping Y being passable into the function as above.

No, we want to tell any user of our code that within the functions "foo" and "bar" we do not change the value, if they pass Y to us with 42, when the function is complete Y will stil contain 42.  If the value could potentially change we would not be able to use "const" that's the purpose of passing const in this case.

Passing by reference is just to save us the time, effort and delay in allocating memory and taking a copy of the parameter before moving into the body of the function, so:

void bar (const int p_Y)

Would be the same operation as above, we tell the user we don't change the value of the parameter, but we do because we take a copy of the value being passed in and operate upon it.

The communication we get with this is very useful.

But of course, if we're using threaded programming and we pass a reference to a value at time point A, then sometime later elsewhere edit the referenced value, we may run into unexpected behaviour, so there is an argument sometimes to take a copy at the point of instantiating the child function, in the most part however, passing by reference is considered the norm.

Monday, 26 March 2018

C++ : Pass-By-Reference Or Die

Before today's Post, I'm on a mission folks, to get 1000 subs on YouTube.  If only 5% of viewers here subscribed we've have met this target in one month...



I've just had group code review of one of my personal projects, and been rather surprised by the vitriol levelled at one of my practices.... Pass by Reference.

The reviewer, one of a group of peers, has had major issues with the project (my personal) insistance on passing by reference wherever possible, in C++ this takes the form of an additional ampersand on parameter definitions; maybe this was the chaps problem, he has to type an ampersand?

So his problem?  Well, without the actual code we'll simplify and use the Compiler Explorer (from Godbolt.org) and we'll take up their basic square function example, it starts up thus:

Giving the assembler:


On the right, and this chap had taken time to prepare a whole slide show of functions, usually simple, and present them at this code review, showing this kind of thing.  His point... Well the very same C++ but with a pass by reference:


Turns up more lines of assembler:


He's got me right, right, I'm taking more time, I'm slowing everything down, by my not taking a copy of everything and using less memory I'm slowing things down....

This is where the sort of power play turned, I allowed him to present everything, I never interjected, never spoke, I allowed him to speak to the whole group.  We've hired a venue for this, we're meeting live for the first time.  This has to be good.... A couple of the chaps who can already see the fault in the complainers logic were smirking, but we let him finish.

Triumphant, he has won the day, he will not carry the torch of coding standard gods...  WRONG.

I pulled over the presentation laptop, opened godbolt.org myself... Added the ampersand to the "num" and let it produce the above assembler... The chap was smirking completely from ear to ear, he knew he had me...

And then I typed three characters....

-O2

Yes, I told the compiler to optimize, and this happened...


Remarkably small code wouldn't you say?  I still haven't spoken, but I turn the laptop back to the presenter and just sit there.

There's a noticable snigger from those in the know, older-wiser heads then my own I hasten to add.  But this young chap is now looking from me to the screen to the overhead projection and back with a mix of fury and completely puzzlement, he'd checked everything, he's dotted every j and crossed every t, he had me down pat, he wanted to usurp me.

Except, he's never ever, been willing to listen, to learn or to experiment, "code runs, that'll do" is very much his style (and Kyle if you're reading, yes I'm talking about you) but getting code to run is not enough, understanding the code you've written is often only just enough, but getting it to run everywhere, the same way, that's an art.  Debug, Release, Optimised, Unoptimised, automatically profiled, link database and continune they're all subtly different.  Just listing one thing out, the only thing you've looked at; because it backs up your point of view; is not enough you have to look around and see the holistic picture.

And optimised without a pass-by-reference?


Spookily similar code in this case, but often times pass-by-reference is prefered, using const-correctness is prefered it communicates a meaning.

For instance in the "square" function above, how does the caller know that the parameter "num" is not altered in value?  How does the caller know it returns the new value only?  It could be returning an error status code and the parameter altered in value!  You don't know, but making the parameter const and a reference you start to communicate more firmly the intent of your code.

Thursday, 27 October 2016

Administrator : Linux Network File System (NFS) Mounted Drives

Over the next few days I'm planning to bring you at least three videos about sharing files between different systems, specifically Windows and Linux... Today the easiest (at least for me) Linux to Linux sharing.

For this you will need SSH access and a user account on the remote system, and sudo (root) rights to both machines.  I'm running Ubuntu machines here, both for the client and the server, which variant (32/64) makes no difference.

The Server
sudo apt-get update
sudo apt-get install nfs-common nfs-kernel-server

We need the nfs-kernel-server here, and it will run as a service, once it's all installed we need to make a folder, I create them like this, making it owned by myself:

sudo mkdir /media/xelous
sudo chown xelous /media/xelous

Then I edit:

sudo nano /etc/exports

And I add to it:

/media/xelous     150.0.8.*(rw,no_root_squash,async)

This is the local folder we're mounting, and we're making it available to ALL the machines on the "150.0.8.1 to 150.0.8.255" range of IP addresses.

Saving this file, I then need to restart the whole machine, or just the service:

sudo /etc/init.d/nfs-kernel-server restart

You can then run:

showmount -e

To see the local mount you've just created, if you have an issue, and it doesn't show up, check the above again... because it does work, honest.... The most common problem is permissions on the folder you've created, sometimes on systems you are not the administrator on, it's best to share a folder from your /home directory.

The Client
The client is a simpler installation:

sudo apt-get update
sudo apt-get install nfs-common

Then you can check the remote mount, lets assume the server is on IP 150.0.8.40:

showmount -e 150.0.8.40

You should see the remote mount you created on the remote machine:

Lets create a folder locally, into which we'll mount the remote folder:

sudo mkdir -p /media/remote
sudo chown xelous /media/remote

Now, I happen to be the user "xelous" on both machines, but change your username for the local or remote machines... Mine is not best practice here, as they just have different passwords....

To mount the remote folder locally:

sudo mount 150.0.8.40:/media/xelous /media/remote

So, this is mounting the remote to the local, on the local machine I can then just hop into that folder and work, knowing all the files are trickling out over the network and into that remote machine.

This is very useful if you're going to run a thin client system, or are working on a machine with no, or read-only, local storage.

Why does this exist?
The driver behind this was my main development machine running out of disk space, and my not being allowed to install a new drive... yes, go figure (don't worry, I have asked the fair fellows of IT for access to my BIOS again - Yes, I'm still on a machine with a BIOS not UEFI, don't laugh).

So, with my workstation critically low on disk space, where was I going to put everything?... Well, on another Linux machine I have on the network of course, a big fat server with a slow CPU but oodles of storage.