Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ deleted new operator but can create shared_ptr

I tried looking for an answer, but couldn't find anything helpful to understand what happens behind the scenes.

Assuming that we have the following:

class Base
{
public:
    virtual int request() = 0; 
    void* operator new(long unsigned int size) = delete;
};


class Derived final : public Base
{
public:
    int request() override;
};

int Derived::request()
{
    return 2;
}

On the base class I have deleted the new operator because I don't want to be able to create pointers. I know it might not make any sense, it is just an experiment.

When I call g++ gives me a compilation error to tell me that the new operator is deleted. Exactly what I expected.

int main()
{
    auto d =  std::make_unique<Derived>();
    int value = d->request();
    std::cout << "Request value is " << value << "." << std::endl;

    return 0;
}

But if I create a shared_ptr the code compiles and runs fine.

    auto d =  std::make_shared<Derived>();

Why is this code valid when creating shared pointers. The operator is not being used in this case?

like image 893
user1908349 Avatar asked Dec 03 '18 13:12

user1908349


People also ask

Do I need to delete a shared_ptr?

The purpose of shared_ptr is to manage an object that no one "person" has the right or responsibility to delete, because there could be others sharing ownership. So you shouldn't ever want to, either.

Why is shared_ptr unique deprecated?

What is the technical problem with std::shared_ptr::unique() that is the reason for its deprecation in C++17? this function is deprecated as of C++17 because use_count is only an approximation in multi-threaded environment.

Can shared_ptr be copied?

The ownership of an object can only be shared with another shared_ptr by copy constructing or copy assigning its value to another shared_ptr . Constructing a new shared_ptr using the raw underlying pointer owned by another shared_ptr leads to undefined behavior.

Can shared_ptr be Nullptr?

A null shared_ptr does serve the same purpose as a raw null pointer. It might indicate the non-availability of data. However, for the most part, there is no reason for a null shared_ptr to possess a control block or a managed nullptr .


1 Answers

std::make_shared use global placement new version of the operator new, by std::allocator::construct

It is necessary to store object and atomic reference counter in the same block of memory, so that shared_ptr template works almost equal to intrusive smart pointer.

You can not prevent std::make_shared to construct a smart pointer.

like image 50
Victor Gubin Avatar answered Sep 19 '22 17:09

Victor Gubin