Jump to content

  • Log In with Google      Sign In   
  • Create Account

Interested in a FREE copy of HTML5 game maker Construct 2?

We'll be giving away three Personal Edition licences in next Tuesday's GDNet Direct email newsletter!

Sign up from the right-hand sidebar on our homepage and read Tuesday's newsletter for details!


We're also offering banner ads on our site from just $5! 1. Details HERE. 2. GDNet+ Subscriptions HERE. 3. Ad upload HERE.


Smart pointer obligating heap allocation when not needed..what am I doing wrong?


Old topic!
Guest, the last post of this topic is over 60 days old and at this point you may not reply in this topic. If you wish to continue this conversation start a new topic.

  • You cannot reply to this topic
10 replies to this topic

#1 Icebone1000   Members   -  Reputation: 1113

Like
0Likes
Like

Posted 24 March 2013 - 04:21 PM

So, in the current rendering engine Im doing, I employed smart pointers (mainly boost::shared_ptr). It gives me lots of flexibility, as I dont need to  care about mem and dont need to worry about getting my pointer corrupted all of sudden, and the data is really supposed to be shared around  to avoid duplicates.

Than on the higher lvl module, who uses the "engine", I figured out Im obligated to use heap allocation even if I dont need (for example, if I know the max number of certain resource).

 

So, shared_ptr are already being very useful, but have this lil annoying detail..Say I have a Cache class or something who stores a fixed size of known data ( on a higher lvl ), that "cache" would control the mem for this one data, but I cant have this data shared with a shared pointer, so Im obligated to do heap allocations due a shared pointer...

 

Where did I "shit" myself on the foot? Shouldnt I ever use smart pointer on lower lvls modules?

I know that stuff like that should provide custom mem allocation mechanisms, but that subject is way over my head right now. Can anyone opine?

 

 



Sponsor:

#2 Servant of the Lord   Crossbones+   -  Reputation: 20300

Like
0Likes
Like

Posted 24 March 2013 - 04:45 PM

Your cache class should own a shared_ptr, and it should hand out weak_ptrs.
shared_ptr implies ownership and access, weak_ptr implies access but not ownership. unique_ptr imples unique ownership and unique access.

You said, "and the data is really supposed to be shared around to avoid duplicates.", just incase you don't know, shared_ptr only shares the same variable when you tell it to.
If you do:

 

boost::shared_ptr<MyClass> ptrA = boost::make_shared<MyClass>(...);
boost::shared_ptr<MyClass> ptrB = boost::make_shared<MyClass>(...);
boost::shared_ptr<MyClass> ptrC = ptrA;

 

ptrA and ptrC point to the same MyClass. ptrB is an entirely different variable that points to a different MyClass.

You probably already know that, but I figured I'd mention it just incase.

You might also want to look into flyweight.

 

I also might be misunderstanding what you mean. Could you give an example of your problem? 'heap' memory means dynamic memory, IIRC. Shared pointers only operate on heap memory. Did you mean you have variables on the stack that you want to give shared access to? If so, use raw pointers (normal C or C++ pointers). Raw pointers aren't evil, they're just another tool in your toolbox. Not every use of pointers are supposed to be replaced by smart pointers.


Edited by Servant of the Lord, 24 March 2013 - 04:49 PM.

It's perfectly fine to abbreviate my username to 'Servant' rather than copy+pasting it all the time.
All glory be to the Man at the right hand... On David's throne the King will reign, and the Government will rest upon His shoulders. All the earth will see the salvation of God.
Of Stranger Flames - [indie turn-based rpg set in a para-historical French colony] | Indie RPG development journal

[Fly with me on Twitter] [Google+] [My broken website]

[Need web hosting? I personally like A Small Orange]


#3 Icebone1000   Members   -  Reputation: 1113

Like
0Likes
Like

Posted 24 March 2013 - 05:11 PM

Your cache class should own a shared_ptr, and it should hand out weak_ptrs.
shared_ptr implies ownership and access, weak_ptr implies access but not ownership. unique_ptr imples unique ownership and unique access.

You said, "and the data is really supposed to be shared around to avoid duplicates.", just incase you don't know, shared_ptr only shares the same variable when you tell it to.
If you do:

 

boost::shared_ptr<MyClass> ptrA = boost::make_shared<MyClass>(...);
boost::shared_ptr<MyClass> ptrB = boost::make_shared<MyClass>(...);
boost::shared_ptr<MyClass> ptrC = ptrA;

 

ptrA and ptrC point to the same MyClass. ptrB is an entirely different variable that points to a different MyClass.

You probably already know that, but I figured I'd mention it just incase.

You might also want to look into flyweight.

 

I also might be misunderstanding what you mean. Could you give an example of your problem? 'heap' memory means dynamic memory, IIRC. Shared pointers only operate on heap memory. Did you mean you have variables on the stack that you want to give shared access to? If so, use raw pointers (normal C or C++ pointers). Raw pointers aren't evil, they're just another tool in your toolbox. Not every use of pointers are supposed to be replaced by smart pointers.

I have a low level system who use shared pointers, this system by itself shares data trough shared pointers. But data isnt created by thys system, it comes from higher lvls systems who will be using it. What is bothering is that by doing that Im obligating heap allocation in the higher lvl module, otherwise I cant insert data to the low lvl module. Resuming..


Edited by Icebone1000, 24 March 2013 - 05:12 PM.


#4 SiCrane   Moderators   -  Reputation: 9626

Like
5Likes
Like

Posted 24 March 2013 - 05:17 PM

shared_ptrs don't require the pointers they manage to be on the heap. When you create a smart pointer you give it two things: a pointer and a deleter, the function object that cleans up the pointer when you're done with it. By default the deleter just calls delete on the pointer. However, you can set it do something else, like a clean up function from a C library. This includes a no-op if you don't want any clean up to be done.

#5 Servant of the Lord   Crossbones+   -  Reputation: 20300

Like
0Likes
Like

Posted 24 March 2013 - 05:20 PM

shared_ptrs don't require the pointers they manage to be on the heap. When you create a smart pointer you give it two things: a pointer and a deleter, the function object that cleans up the pointer when you're done with it. By default the deleter just calls delete on the pointer. However, you can set it do something else, like a clean up function from a C library. This includes a no-op if you don't want any clean up to be done.

 

*smacks forehead* I hadn't considered a no-op deleter. +1


It's perfectly fine to abbreviate my username to 'Servant' rather than copy+pasting it all the time.
All glory be to the Man at the right hand... On David's throne the King will reign, and the Government will rest upon His shoulders. All the earth will see the salvation of God.
Of Stranger Flames - [indie turn-based rpg set in a para-historical French colony] | Indie RPG development journal

[Fly with me on Twitter] [Google+] [My broken website]

[Need web hosting? I personally like A Small Orange]


#6 Icebone1000   Members   -  Reputation: 1113

Like
0Likes
Like

Posted 24 March 2013 - 05:27 PM

sorry my imbecility, but what the hell is a "no-op"?



#7 SiCrane   Moderators   -  Reputation: 9626

Like
0Likes
Like

Posted 24 March 2013 - 05:29 PM

"No-op" is short for "no operation". In this case a function that does nothing.

#8 Servant of the Lord   Crossbones+   -  Reputation: 20300

Like
1Likes
Like

Posted 24 March 2013 - 06:54 PM

SiCrane is saying you can use the second template parameter of smart pointers to give a fake custom deleting function (in this case, a functor), so shared_ptr can work with stack-allocated variables.
 
//Functor for pretending to delete a block of stack-allocated memory, instead of using the default deleter provided by smart pointers.
//This can be passed as the second parameter of a smart pointer.
struct do_not_delete
{
    do_not_delete() { }
    
    void operator()(void*) const
    {
        //Do nothing. Let the stack free the memory when it's ready.
    }
};

{
	std::string onTheStack = "Test";
	{
		std::shared_ptr<std::string> mySharedPtr(&onTheStack, do_not_delete());	
		std::cout << *mySharedPtr << std::endl;
	}
	//mySharedPtr goes out of scope here, and calls 'do_not_delete(ptr)' to free the memory,
	//but do_not_delete doesn't free it, safely letting the stack-allocated memory continue to exist.

	std::cout << onTheStack << std::endl; //The stack-allocated memory continues to work just fine.
}
(I'm using C++11's standard shared pointers, but it should be roughly the same for boost smart pointers)

Ofcourse, now you have to be sure that 'onTheStack' lasts longer than 'mySharedPtr', or hard-to-track bugs result.

However, I think your low level functions shouldn't take pointers at all! I think almost every function should take parameters by const reference, unless something else is required. Then, whether you pass in actual stack-allocated or heap-allocated, it doesn't matter, and the function doesn't care.
void myFunc(const std::string &str);

std::string stackAllocated;
myFunc(stackAllocated);

std::shared_ptr<std::string> heapAllocatedShared = std::make_shared<std::string>();
myFunc(*heapAllocatedShared);

std::unique_ptr<std::string> heapAllocatedUnique = make_unique<std::string>();
myFunc(*heapAllocatedUnique);
You said that your low-level system "shares" data. Does it 'own' the data, or just 'use' the data? If it doesn't own it, it shouldn't be a shared_ptr, because shared_ptr means shared ownership. If something else owns it higher up, just use references or raw pointers lower down, unless it is possible for the lifetime of the system's access to the pointers to extend beyond the lifetime of the data passed in. If the lower down system uses it, but does not own it, and is likely to keep the pointer around for longer than the lifetime of the memory allocated, it might be worth considering whether that lower-level system should actually own it, with higher level code creating the object and giving up ownership of it to the lower system. Or maybe the lower-level system actually is doing more than it should be doing? Software architecture-design isn't my strong point.

Edited by Servant of the Lord, 24 March 2013 - 06:58 PM.

It's perfectly fine to abbreviate my username to 'Servant' rather than copy+pasting it all the time.
All glory be to the Man at the right hand... On David's throne the King will reign, and the Government will rest upon His shoulders. All the earth will see the salvation of God.
Of Stranger Flames - [indie turn-based rpg set in a para-historical French colony] | Indie RPG development journal

[Fly with me on Twitter] [Google+] [My broken website]

[Need web hosting? I personally like A Small Orange]


#9 EddieV223   Members   -  Reputation: 1406

Like
-2Likes
Like

Posted 24 March 2013 - 08:07 PM

Lol all this topic has gone way off course, if you're pointing to stack memory use a naked pointer, there isn't any reason to use a shared_ptr in this case.  If you wanted to you could use a reference, but there isn't much benefit in that except some cleaner syntax, but then you can't null the reference if you needed to.

 

If I were you either use a smart pointer to an std::array ( using the heap ), or just pass the address ( naked pointer to ) your std::array or c style array ( on the stack ).


Edited by EddieV223, 24 March 2013 - 09:32 PM.

If this post or signature was helpful and/or constructive please give rep.

 

// C++ Video tutorials

http://www.youtube.com/watch?v=Wo60USYV9Ik

 

// Easy to learn 2D Game Library c++

SFML2.1 Download http://www.sfml-dev.org/download.php

SFML2.1 Tutorials http://www.sfml-dev.org/tutorials/2.1/

 

// SFML 2 book

http://www.amazon.com/gp/product/1849696845/ref=as_li_ss_tl?ie=UTF8&camp=1789&creative=390957&creativeASIN=1849696845&linkCode=as2&tag=gamer2creator-20

 


#10 BitMaster   Crossbones+   -  Reputation: 4228

Like
1Likes
Like

Posted 25 March 2013 - 01:56 AM

Lol all this topic has gone way off course, if you're pointing to stack memory use a naked pointer, there isn't any reason to use a shared_ptr in this case.  If you wanted to you could use a reference, but there isn't much benefit in that except some cleaner syntax, but then you can't null the reference if you needed to.

That works in trivial cases but is not useful advise for the general case. Just because something can be allocated on stack does not mean every instance you have to work with is allocated on the stack. I have frequently worked in systems where instances might have to be deleted by library function A, library function B, by the standard delete or not at all (because they are a static instance on the stack).

#11 EddieV223   Members   -  Reputation: 1406

Like
0Likes
Like

Posted 25 March 2013 - 11:31 AM

Lol all this topic has gone way off course, if you're pointing to stack memory use a naked pointer, there isn't any reason to use a shared_ptr in this case.  If you wanted to you could use a reference, but there isn't much benefit in that except some cleaner syntax, but then you can't null the reference if you needed to.

That works in trivial cases but is not useful advise for the general case. Just because something can be allocated on stack does not mean every instance you have to work with is allocated on the stack. I have frequently worked in systems where instances might have to be deleted by library function A, library function B, by the standard delete or not at all (because they are a static instance on the stack).

I was speaking specifically about the OP's case.


If this post or signature was helpful and/or constructive please give rep.

 

// C++ Video tutorials

http://www.youtube.com/watch?v=Wo60USYV9Ik

 

// Easy to learn 2D Game Library c++

SFML2.1 Download http://www.sfml-dev.org/download.php

SFML2.1 Tutorials http://www.sfml-dev.org/tutorials/2.1/

 

// SFML 2 book

http://www.amazon.com/gp/product/1849696845/ref=as_li_ss_tl?ie=UTF8&camp=1789&creative=390957&creativeASIN=1849696845&linkCode=as2&tag=gamer2creator-20

 





Old topic!
Guest, the last post of this topic is over 60 days old and at this point you may not reply in this topic. If you wish to continue this conversation start a new topic.



PARTNERS