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

Started by
9 comments, last by EddieV223 11 years, 1 month ago

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?

Advertisement

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.

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..

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.

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

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

"No-op" is short for "no operation". In this case a function that does nothing.
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.

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 ).

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.2 Download http://www.sfml-dev.org/download.php

SFML2.2 Tutorials http://www.sfml-dev.org/tutorials/2.2/

// Excellent 2d physics library Box2D

http://box2d.org/about/

// 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

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).

This topic is closed to new replies.

Advertisement