简体   繁体   English

为什么我可以通过原始指针而不是 shared_ptr 修改 object?

[英]Why can I modify an object through a raw pointer but not a shared_ptr?

So, I would like to use a function that modifies an object through a shared_ptr .所以,我想使用 function 通过shared_ptr修改 object 。

I've got this class Foo :我有这个 class Foo

class Foo
{
private:
    bool i = false;

public:
    void activate()
    {
        i = true;
    }

    bool isActive()
    {
        return i;
    }
};

Nothing too fancy.没什么太花哨的。 My goal is to modify a Foo object through a pointer, like so:我的目标是通过指针修改Foo object ,如下所示:

Foo foo;

std::shared_ptr<Foo> ptrfoo = std::make_shared<Foo>(foo);
ptrfoo->activate();

// "foo.isActive" returns false here

Sadly, foo.isActive returns false when I want it to return true .可悲的是,当我希望foo.isActive返回false时,它会返回true But the thing is, it works with raw pointers:但问题是,它适用于原始指针:

Foo foo;

Foo* ptrfoo = &foo;
ptrfoo->activate();

// "foo.isActive" returns true here

So why does that happen, and can I modify the object through a shared_ptr ?那么为什么会发生这种情况,我可以通过shared_ptr修改 object 吗? If so, how can I do that?如果是这样,我该怎么做?

Smart pointers are owning pointers.智能指针是拥有指针。 Because they own the memory they point to when you do因为他们拥有 memory,当您这样做时,他们会指出

std::shared_ptr<Foo> ptrfoo = std::make_shared<Foo>(foo);

you don't get a pointer to foo but instead you get a pointer to an object that is a copy of foo .您没有得到指向foo的指针,而是得到指向 object 的指针,它是foo的副本。 Anything you do to ptrfoo will not effect foo .您对ptrfoo所做的任何事情都不会影响foo This is one of the main differences between raw pointers and smart pointers.这是原始指针和智能指针之间的主要区别之一。 You can get a smart pointer to act like a raw pointer, but that is a lot of work and non owning raw pointers are okay so it's not really worth trying to modify smart pointers to get that behavior.您可以让智能指针像原始指针一样工作,但这需要大量工作,而且非拥有原始指针是可以的,因此尝试修改智能指针以获得这种行为并不值得。

In the first block, the shared_ptr points to a copy of foo .在第一个块中, shared_ptr指向foo的副本。
In the second block, the pointer points to foo .在第二个块中,指针指向foo

You can verify that by using:您可以使用以下方法进行验证:

std::cout << "Address of foo: " << &foo << std::endl;
std::cout << "Pointer from shared_ptr: " << ptrfoo->get() << std::endl;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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