0

Let me start off by saying that I'm very new to C++ currently - i have previously only really worked with python and javascript (quite a lot of exposure to python) and so, now that I'm learning C++ to expand my knowledge and understanding of lower level programming concepts I wanted to reach out and ask a specific question here.

Of course, with python I have not needed to worry at all about memory allocation, object copies, passing by value/reference, etc. its a whole new world! (very exciting :D)

The way i learn best is to learn by doing, so i have created a relatively simple blockchain proof of concept.

I wont paste in all my code here, as its a fair amount already, but what I want to check is specifically around how copies of objects are handled.

I am not using any dynamic memory allocation either via new/delete or shared_ptr/make_shared thus far in my code, and if i've understood correctly, all of my objects are being created on the stack - as such once the object goes out of scope, this will be automatically destructed (is this right?).

Let me provide an example here and explain what my specific question is. Consider the following code blocks:

void Blockchain::AddBlock(Block bBlock)
{
    if (bBlock.ValidateBlock(_vChain))
    {
        _vChain.push_back(bBlock);
        cout << "Chain Length: " << _vChain.size() << endl;
    }
    else
    {
        throw Exceptions::ValidationError();
    }
}

void Blockchain::AddTransaction(Transaction &tTransaction)
{
    cout << "Adding Transaction to block number " << _vChain.size() + 1 << endl;
    bool IsValidated = _ValidateTransaction(tTransaction);
    if (!IsValidated)
    {
        cout << "... not valid" << endl;
    }
    else
    {
        // cout << "Valid";
        int ChainLength = _vTransaction.size();
        if (ChainLength < BlockchainConstants::MAX_BLOCK_SIZE)
        {
            _vTransaction.push_back(tTransaction);
        }
        else
        {
            uint32_t NewIndex = _vChain.size();
            Block NextBlock = Block(NewIndex, _vTransaction);
            NextBlock.sPrevHash = GetLastBlock().GetHash();
            AddBlock(NextBlock);
            _vTransaction.clear();
            _vTransaction.push_back(tTransaction);
        }
    }
}

Again, if i've understood correctly, in the above block of code that i've written, once the transaction pool has hit its max capacity (thus triggering the else condition), I am creating a block object based on the transaction pool and the index, this is the first instance. When i call AddBlock() I am passing the object by value, thus creating a copy of the object. Within AddBlock() method i am validating the block, and again pushing the object back into the vector _vChain (again, creating a copy). My question is, at the end of that whole process, am I left with any more than one object? My assumption is that the first object created gets destructed at the end of the else condition in AddTransaction() and the second copy is destructed at the end of AddBlock(), leaving me with just 1 instance of the object in the vector _vChain.

Is my thinking correct here? Apologies for the long question, I just wanted to make sure i had all of the details here for you guys - let me know if there is anything else you need to know to help me out. Would appreciate any help at all!

Cheers

Calleb213
  • 151
  • 1
  • 9
  • You should learn about the scope of variable. Where `Block bBlock` in `AddBlock()` will be destructed after going out of the function. – Louis Go Jan 03 '22 at 02:12
  • (Tangentially related, but it'd be a lot easier to read the question if it was just the question--currently it's a lot of other words, and the question itself is in a wall of text.) – Dave Newton Jan 03 '22 at 02:12
  • @DaveNewton Thanks for that advice - I have been downvoted and seen others downvoted in the past for lack of detail, so maybe I overcompensated :) I'm just really looking for a bit of help and wanted it all to be clear, and make sure all understand I have tried to work this out myself and not just asking here first thing - regardless, is my question ultimately clear or do I need to clarify something? – Calleb213 Jan 03 '22 at 02:15
  • @LouisGo Yes, this is ultimately what I am trying to understand. As this is a void function - and i'm not returning the bBlock object afterwards, does that mean that the scope ends at the end of the AddBlock method? – Calleb213 Jan 03 '22 at 02:17
  • @LouisGo I guess that opens up to another potential clarification (potentially tangential as well), if this function were to return a Block type and I returned bBlock at the end of the method, would this increase the scope of bBlock, or would it create another copy which would have its own scope and the bBlock object itself would be destructed? – Calleb213 Jan 03 '22 at 02:19
  • I'm completely self taught programmer (not even really a programmer, i just love it) so i've not had any formal teaching - sorry for any gaps there and thanks for any help! – Calleb213 Jan 03 '22 at 02:21
  • @Calleb213 `void Blockchain::AddBlock(Block bBlock)` -- You are passing `Block` by value. This means that a temporary copy is made. This is why you should never use other languages as a model in writing C++ code. If you use other languages as a model, you will end up with inefficient code, buggy code, or code that looks weird to a C++ programmer. As to how many copies, C++ has a [as-if](https://en.cppreference.com/w/cpp/language/as_if) rule. The compiler is free to optimize the code in any way it sees fit, including eliminating copies where it can. – PaulMcKenzie Jan 03 '22 at 05:18
  • @PaulMcKenzie thanks for your comment - yes, I didnt learn python for the sake of then learning C++ i learned python because i wanted to learn python, and then wanted to learn something else, so went to C++. I am fully aware it is completely different and concepts of python should not be overlaid on C++ willy nilly. Thanks for the link - i'll read through! – Calleb213 Jan 03 '22 at 12:15

1 Answers1

0

Your question is a bit unclear since I'm not sure why you'd like to know how many copies are there. Edit your question if you'd like to know more explicit question. I smell XY-problem here.

What you need to know is the variable scope.

I assume _vChain is a class member or global variable somehere so _vChain will have a copy of bBlock if validation is passed in AddBlock(). The input argument will be destructed after leaving the function.

If you want to see the behavior, the most simple way is to place std::cout in both of the constructor and destructor to track the construction and destruction of Block.

Also I suggest to pick a beginning programmer's book in The Definitive C++ Book Guide and List.

Louis Go
  • 2,213
  • 2
  • 16
  • 29
  • Thanks! Thats pretty much what I wanted to confirm. Not sure what the XY Problem really is but reading the link you pasted, it is that i'm asking about my solution of the problem? I dont think that is really the case however, my question, albeit long winded maybe, was meant to be more generally about copies and how they are handled in this kind of scenario. Its not a problem as far as I can see, I'm just asking to understand, sorry - as i've said in my comments above, i just genuinely find programming extremely interesting and want to understand as much as I can. Will narrow down my questions. – Calleb213 Jan 03 '22 at 02:33
  • And sorry, yes thats correct, _vChain is a class member – Calleb213 Jan 03 '22 at 02:42
  • @Calleb213 Good to know I answered your question. Still I suggest to take a book as reference. – Louis Go Jan 03 '22 at 02:56
  • Cheers for the other resource as well @LouisGo – Calleb213 Jan 03 '22 at 12:18
  • Do you have a book that you recommend? I have Clean Code by Uncle Bob already – Calleb213 Jan 03 '22 at 12:19
  • @Calleb213 That's a "programming in general" book (ignoring some of his more problematic takes), the suggestion was to get a C++ book. – Dave Newton Jan 03 '22 at 14:27
  • @DaveNewton - This is what i'm asking - any recommendation for a good C++ book? – Calleb213 Jan 03 '22 at 15:11
  • @Calleb213 One of the ones on that list, targeted towards your experience level? – Dave Newton Jan 03 '22 at 15:25
  • @DaveNewton Sorry! my fault, missed the book list at the end! Thanks – Calleb213 Jan 03 '22 at 15:46