简体   繁体   中英

C++ shared_ptr void

I am facing an issue. I created a c++ code snippet from an automated script. In that, I create an object say x and it's handler as xx. It is around 2000 handlers. Out of that there is a chance that the name of object is x and handler name is mistakenly x, instead off xx. The reverse is not happening. Since the handler is of shared_ptr<void>, it is accepting that without any compiler error. What I am looking for is to ensure a compiler error and avoid a run time error. The code is as follows.

#include <memory>
#include <iostream>
#include <string>   

using namespace std;

class A
{
public:
    void foo()
    {
        std::cout << "Foo";
    }

};
typedef shared_ptr<A> A_SharedPtr;
typedef shared_ptr<void> A_Handler;

struct packet
{
    A_SharedPtr mem_1;
    A_Handler   mem_2;
    packet(A_SharedPtr a1, A_Handler a2)
    {
        mem_1 = a1;
        mem_2 = a2;
    }
};


int main() {
    A_SharedPtr x;
    A_Handler xx;

    packet p1(x, x); //POTENTIAL ERROR WHICH LEADS TO RUNTIME EXCEPTION
    packet p2(x, xx);//CORRECT ONE

}

Could you suggest, a programmer will get a compile error when try

packet p1(x, x);

saying second argument is wrong?

You might delete the unwanted overload

struct packet
{
    A_SharedPtr mem_1;
    A_Handler   mem_2;
    packet(A_SharedPtr, A_SharedPtr) = delete;
    packet(A_SharedPtr a1, A_Handler a2);
};

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