Putting the 'role' back in role-playing games since 2002.
Donate to Codex
Good Old Games
  • Welcome to rpgcodex.net, a site dedicated to discussing computer based role-playing games in a free and open fashion. We're less strict than other forums, but please refer to the rules.

    "This message is awaiting moderator approval": All new users must pass through our moderation queue before they will be able to post normally. Until your account has "passed" your posts will only be visible to yourself (and moderators) until they are approved. Give us a week to get around to approving / deleting / ignoring your mundane opinion on crap before hassling us about it. Once you have passed the moderation period (think of it as a test), you will be able to post normally, just like all the other retards.

[deso's thread for c++ doubts] Can somebody explain vector specialization?

desocupado

Magister
Joined
Nov 17, 2008
Messages
1,802
C++

Say I call a function, and inside that function I create a pointer to something, store it in a vector (vector was passed by reference, so it exists after the function call is over) and then quit the function call.

The pointer created exists only inside the vector now, since it was created inside the function's scope.

If I just remove the pointer from the vector using vector.erase(begin()+position), does the memory alocated by whatever that pointer points to is liberated?
 

racofer

Thread Incliner
Joined
Apr 5, 2008
Messages
25,605
Location
Your ignore list.
Nope, it's still allocated.

You have to manually free that allocated memory of that pointer. If you just remove the pointer from the vector/array, you're merely clearing the 32/64 bits used by that pointer in the array, but not the memory area that that pointer points to.
 

DraQ

Arcane
Joined
Oct 24, 2007
Messages
32,828
Location
Chrząszczyżewoszyce, powiat Łękołody
AFAIK nope. You need to free that memory manually if you've allocated it with new, malloc or realloc.
Machine doesn't keep track of whether you're using pointer to the same address somewhere else in your code, so it doesn't deallocate automatically, as it would if you erased an actual variable from the container or exited the scope of a variable.
 

crojipjip

Developer
Übermensch
Joined
Jan 11, 2012
Messages
4,253
AFAIK nope. You need to free that memory manually if you've allocated it with new, malloc or realloc.
Machine doesn't keep track of whether you're using pointer to the same address somewhere else in your code, so it doesn't deallocate automatically, as it would if you erased an actual variable from the container or exited the scope of a variable.

allow me to explain. containers contain. if you push objects into them by value, you have a copy. pointers point. 4 bytes are 4 bytes is an int is integer 32. is 32 bit operating system.

pointers are the size of integers. but the moment you say > 4 bytes, you already save space by using pointer or reference. by saving space you, have less to process/create and save time in processing thus speed. the language C/C++ trust the programmer. you are suppose to make the benefit happen and thus are burdened of when to clean things up. it feels good to clean things up. but it also feels good to know you keep the memory you want around, around.
 

crojipjip

Developer
Übermensch
Joined
Jan 11, 2012
Messages
4,253
AFAIK nope. You need to free that memory manually if you've allocated it with new, malloc or realloc.
Machine doesn't keep track of whether you're using pointer to the same address somewhere else in your code, so it doesn't deallocate automatically, as it would if you erased an actual variable from the container or exited the scope of a variable.

allow me to explain. containers contain. if you push objects into them by value, you have a copy. pointers point. 4 bytes are 4 bytes is an int is integer 32. is 32 bit operating system.

pointers are the size of integers. but the moment you say > 4 bytes, you already save space by using pointer or reference. by saving space you, have less to process/create and save time in processing thus speed. the language C/C++ trust the programmer. you are suppose to make the benefit happen and thus are burdened of when to clean things up. it feels good to clean things up. but it also feels good to know you keep the memory you want around, around.

in response to crojipjip's post. you could store containers inside a vector that are added by value but which free assigned pointers. just know what you are using yo.
 

J1M

Arcane
Joined
May 14, 2008
Messages
14,626
If you use new somewhere, you eventually need to use delete.
 

No soup for you!

Guest
Note that you could get the deallocation-on-removal behavior by way of a shared_ptr<T>
 

desocupado

Magister
Joined
Nov 17, 2008
Messages
1,802
New doubt.

I wanted to make a item stack. I store my items as objects inside a vector, so I asked Alex how make the item stack, and he talked to me about specializing a vector, so it doesn't take more than one object of the same type, instead, it would take one and adds a number representing the amount or something.

I searched the net, but only found about template specializing, which I don't really see how I could apply it to the vector class.

How do I do that? Can someone explain/link something?
 

crojipjip

Developer
Übermensch
Joined
Jan 11, 2012
Messages
4,253
New doubt.

I wanted to make a item stack. I store my items as objects inside a vector, so I asked Alex how make the item stack, and he talked to me about specializing a vector, so it doesn't take more than one object of the same type, instead, it would take one and adds a number representing the amount or something.

I searched the net, but only found about template specializing, which I don't really see how I could apply it to the vector class.

How do I do that? Can someone explain/link something?

vector<int> (ints only)
vector<char> (chars only)
vector<bool> (bools only)

such a restriction like omg. use critical thinking yo. vectors use templates and store whatever type you specify in the '< >'. <men>/ look at that men vector!

bro I use to be like you. being more interested in what others think of what i think, than getting at actual answers. you have google, don't come to codex to ask what can obviously be a program others have faced. damnit men.

today programming is so well understood for so many different languages you reallly only need a few books to be fully educated. AND if you have access to the world wide web why would you even bother waiting for someone to give you an answer?

what the fuck how to store items? bullshit design ideas like how to add an int between objects, rather than doing size() or length()!

wtf. i hope you have everything paid for, otherwise your struggle will be immense if you don't start acting mature.
 

desocupado

Magister
Joined
Nov 17, 2008
Messages
1,802
Having a single object instead of several and doing .size() would help me out when writing the "Draw" method for the item manager class.

I also don't want to change the vector template, because since the specialization doesn't inherit the functions the vector already has, I would need to re-write the vector class, basically.

I could have dealt with that by just making a class for it, I guess, but Alex said it would be less work, and I wanted to know about it anyway.

So, the original request still stands. (I probably shouldn't be paying so much attention to prosper, anyway)
 

crojipjip

Developer
Übermensch
Joined
Jan 11, 2012
Messages
4,253
Having a single object instead of several and doing .size() would help me out when writing the "Draw" method for the item manager class.

I also don't want to change the vector template, because since the specialization doesn't inherit the functions the vector already has, I would need to re-write the vector class, basically.

I could have dealt with that by just making a class for it, I guess, but Alex said it would be less work, and I wanted to know about it anyway.

So, the original request still stands. (I probably shouldn't be paying so much attention to prosper, anyway)

quit giving reach around to fox news premise. I am trying to tell you what is at fault in your thinking. I think you have a communication problem or you are deliberately misleading us to make your project seem more complicated than it really is. a vector is a vector. size returns the number of items in the container. period. now derp, why can't you see that template specialization isn't what you need?

templates deal with a whole range of types, but mainly enable the programmer to spend less time rewriting code. static compilation or GTFO.

Pick one and stick with it.


14.1 Function templates
14.2 Function template instances
14.3 Template classes
14.4 Expression parameters and template specialization
14.5 Class template specialization
14.6 Partial template specialization
 
Joined
Jan 9, 2011
Messages
2,728
Codex 2012 Codex 2013 Codex 2014 PC RPG Website of the Year, 2015 Codex 2016 - The Age of Grimoire Make the Codex Great Again! Grab the Codex by the pussy Insert Title Here RPG Wokedex Strap Yourselves In Codex Year of the Donut Codex+ Now Streaming! Serpent in the Staglands Dead State Divinity: Original Sin Project: Eternity Torment: Tides of Numenera Wasteland 2 Codex USB, 2014 Shadorwun: Hong Kong Divinity: Original Sin 2 BattleTech Bubbles In Memoria A Beautifully Desolate Campaign Pillars of Eternity 2: Deadfire Pathfinder: Kingmaker Steve gets a Kidney but I don't even get a tag. My team has the sexiest and deadliest waifus you can recruit. Pathfinder: Wrath I'm very into cock and ball torture I helped put crap in Monomyth
If you have class Item, then just inherit it for ItemStack. Add a member _count member, override stuff like GetWeight(), Use() etc. to take into consideration that you operate on multiple items. You may also have to add stuff like Split() and Merge(). You will most likely have to use dynamic_cast at some point with this approach. With that approach you would still have std::vector<Item *>, however some elements would actually be of item ItemStack type. Your Draw() function is most likely virtual so ItemStack should know how to draw itself.

One more thing about this - if you iterate over an std::vector (or any c++ container) you don't need to get its size. You should use iterators instead - see example below:
Code:
typedef std::vector<Item *> ItemVector;
ItemVector myItems; 
/* initialization of vector with your stuff goes here, you could use C++11 uniform initialization syntax if your compiler supports this */
for (ItemVector::const_iterator iter = myItems.begin(); iter != myItems.end(); ++iter) {
   (*items)->Draw(/* context probably goes here */);
}


Read on if your request is about data structures.

STL already has a stack. It is a container adapter so you can use it with any container type as long as it satisfies the criteria.

I recommend that you never use std::vector<bool> as it behaves differently than normal vectors.

The shared_ptr recommendation is a good one for dealing with memory. You don't get it in C++99, but C++11 has it built in. You can also use Boost library to get those. Please be aware that they do introduce some overhead in terms of storage (pointer to your element + reference counter) and performance as you have to call operator->() on the shared_ptr() object. Syntactically you use shared_ptr pretty much the same way you use a plain pointer.

As far as I know Mr. Prosper ignores me, so he will not be able to provide his invaluable comments on the contents of this post.

If you ever want me to review your code or need any C++ advice just PM me.
 

crojipjip

Developer
Übermensch
Joined
Jan 11, 2012
Messages
4,253
Code:
const int defaultCapacity = 8;
class CSlot
{
    public:
    CSlot() : m_count (0), m_capacity(defaultCapacity)
    {
    }
    CSlot(int capacity) : m_count(0), m_capacity(capacity)
    {
    }
 
    void SetCount(int nVal) { m_count = nVal; }
    void SetCapacity(int nVal) { m_capacity = nVal; }
    int GetCount() { return m_count; }
    int GetCapacity() {return m_capacity; }
    void Clean() {
        m_items.clear();
 
    }
 
 
    void AddItem(Item* pItem) {
        if (m_count == 0) {
            int nVal = m_count + pItem->quantity;
            if (nVal <= m_capacity) {
                // do add!
                m_items.push_back(pItem);
                m_count += pItem->quantity;
            }
         
     
        }
        else {
            int nVal = m_count + pItem->quantity;
            if (nVal > m_capacity) {
                // do not add
                return;
            }
         
            m_items.push_back(pItem);
            m_count += pItem->quantity;
        }
    }
 
    private:
    int m_count;
    int m_capacity;
    vector<Item*> m_items;
 
};

With the above code you can store in an inventory slot different stacks of different items.
All you need to do is add an item quantity property to the item class itself. Then program the merge function separate. It is like this: upon detecting a user placing an item into an inventory slot prompt them if they want to merge one or more items present in the slot. you have already told us what you mean by merge. Write a FindItem function that will return items already present in the destination inventory slot, tally them up (and their respective quantity properties) then just submit a single Item* with the sum of the properties..

You should know ahead of time what types of items are the stacking kind as well as made enumerations for them so it would be trivial to do all of what I have said.

*note it may seem drastic that inventory slots are so powerful and able to store many different things in a single space, but you can fix that by playing with the CSlot capacity property.
 

CappenVarra

phase-based phantasmist
Patron
Joined
Mar 14, 2011
Messages
2,912
Location
Ardamai
I apologize in advance for not being constructive, but a voice of conscience won't let me go until I say this: drop C++ (the most prosperous of languages) and run far far away. I know you'll ignore this warning, and be annoyed with my off-topic bullshit - and I accept that. But for the love of Vecna, drop it and save your soul while you can. kthnxbye.
 

Marsal

Arcane
Joined
Oct 2, 2006
Messages
1,304
Look what it did to Prosper! :lol: I am disappointed Prosper isn't using Prolog, though.
 

crojipjip

Developer
Übermensch
Joined
Jan 11, 2012
Messages
4,253
Look what it did to Prosper! :lol: I am disappointed Prosper isn't using Prolog, though.
http://www.rpgcodex.net/forums/inde...than-i-thought-but-here-it-is-for-free.75600/

I tested it and it actually works. Took much longer than I thought though. I also expect there to be a few bugs. so far i haven't found any. w

HOFLm.png
 

CappenVarra

phase-based phantasmist
Patron
Joined
Mar 14, 2011
Messages
2,912
Location
Ardamai
I sit within the umbral embrace and obey the commands of my fingers, dancing gently around the keys that make the compiler happy. There are things crawling over my legs and under the table, an ignored heap of hoarded mewlings and accusation balanced in a red-black tree. Orphaned objects loudly object to my injustices and sins: little endian and little Andyman neigh mournfully through an undoable embrace brought upon by a careless cast. you said he was my friend! you said he could touch my private fields! and look at me now! Memory allocated but never released, falling through blasphemous cracks in the order of the universe, indestructible mementos of not good enough. A pompous boost smart pointer lectures me yet again about the proper ceremony of the imperial court, disgusted by my failure to remember to bow thrice backwards when encountering an animal belonging to the Emperor, and seventimes forwards if it's female or a value type. I beg the compiler for some malloc time together, but she's in a prissy mood. malloc! is that all you can think about! malloc, like a filthy beast of a brute you are! don't you have the decency to turn off the lights first and say "new" nicely? get out of my sight, animal! It's so hard to concentrate when she's like that; I want to tell her I can't turn off the light because it's already off, but her tri-state eyes don't see my way, just pierce me with jagged array glares. I set a breakpoint but it never triggers, and now I can't get out of the chair. The tower of Pisa is in Hanoi is a stack of empty pizza boxes; a stack that refuses to pop. I wish it was a double-ended queue, but it told me it doesn't swing that way. And yet, it swings menacingly above me, threatening to bury me unless I delete my reference to the physical. Which way to go, when you're at a la grange point orbited by azathoth? Which way, when you can't stop hearing the voices of the void pointers? Which which way way??
 

crojipjip

Developer
Übermensch
Joined
Jan 11, 2012
Messages
4,253
I apologize in advance for not being constructive, but a voice of conscience won't let me go until I say this: drop C++ (the most prosperous of languages) and run far far away. I know you'll ignore this warning, and be annoyed with my off-topic bullshit - and I accept that. But for the love of Vecna, drop it and save your soul while you can. kthnxbye.
Ok after reading your story in post #17 I want to know what you mean. What is wrong with C++ other than the learning curve? yes it is very prosperous. for me it required much studying. initially i would just edit sources for d3d9 hacks and d3d9 examples from the d3d9 sdk. moving to opengl was a wonderful experience too.
 

As an Amazon Associate, rpgcodex.net earns from qualifying purchases.
Back
Top Bottom