简体   繁体   中英

Object creates another instance instead of modifying the one that's pointed

In my main I have variables:

ProcessManager mng;
MemoryManager mem;
dysk disk;

and I'm trying to use these pointers (also in main)

std::shared_ptr<MemoryManager> wsk= std::make_shared<MemoryManager>(mem) ;
std::shared_ptr<dysk> wsk_d = std::make_shared<dysk>(disk);

to pass these objects to an instance of my antoher object (through constructor:

Interpreter interpreter(wsk,wsk_d);

but it looks like intepreter creates his own instance of disk, why?

class Interpreter
{
private:
    std::shared_ptr<PCB> pcb;
    std::shared_ptr<MemoryManager> mm;
    std::shared_ptr<dysk> disk;
}

That's what std::make_shared does : Create a new object using the passed arguments to pass to a suitable constructor. In your case a copy-constructor.

That is, the statement

std::shared_ptr<MemoryManager> wsk= std::make_shared<MemoryManager>(mem);

is equivalent to

std::shared_ptr<MemoryManager> wsk(new MemoryManager(mem));

If you want to have your shared pointer reference the existing object then you need to use eg

std::shared_ptr<MemoryManager> wsk(&mem);

But that will bring with it other problems since when the last shared pointer is destructed then it will attempt to free the memory, which is not possible for object not created by new . There are two solutions to this: Either creating a (or using an existing) null-deleter which doesn't actually delete anything; Or by letting the shared pointer handle the complete ownership (from creation to destruction) of the object.

And that's really how you should look at the smart pointers, not as a kind of self-deleting pointer, but in terms of resource ownership .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM