简体   繁体   English

C++ shared_ptr void

[英]C++ shared_ptr void

I am facing an issue.我正面临一个问题。 I created a c++ code snippet from an automated script.我从自动化脚本创建了一个 C++ 代码片段。 In that, I create an object say x and it's handler as xx.在那,我创建了一个对象说 x,它的处理程序为 xx。 It is around 2000 handlers.大约有 2000 个处理程序。 Out of that there is a chance that the name of object is x and handler name is mistakenly x, instead off xx.其中,对象名称有可能是 x,而处理程序名称错误地是 x,而不是 xx。 The reverse is not happening.没有发生相反的情况。 Since the handler is of shared_ptr<void>, it is accepting that without any compiler error.由于处理程序属于 shared_ptr<void>,因此它接受它而没有任何编译器错误。 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您可能会delete不需要的过载

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

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

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