Is there a way to call a function expecting a pointer without creating variable?

前端 未结 2 1366
别跟我提以往
别跟我提以往 2021-01-19 14:56

I have this function call:

uint32_t func(uint32_t* a, uint32_t b)

I want to call it with an integer literal like this:

func         


        
相关标签:
2条回答
  • 2021-01-19 15:29

    A helper class:

    struct int_ptr {
        int v;
    
        operator int *() { return &v; }
    };
    
    int foo(int *a, int b);
    
    void bar()
    {
        foo(int_ptr{0}, 0);
    }
    

    This results in a construction of a temporary int_ptr class, initializing its v member to 0. This gets passed as a parameter to a function that takes an int *, and int_ptr provides a suitable operator * method that passes the right pointer to the function.

    This entire house of cards hinges on the fact that the int_ptr temporary exists until the end of the function call. You should pick a name for the helper class to underline that fact. If you always use it to pass a pointer to 0 to foo, then spell it out:

    struct zero_value_to_foo {
        int v=0;
    
        operator int *() { return &v; }
    };
    
    int foo(int *a, int b);
    
    void bar()
    {
    
        foo(zero_value_to_foo{}, 0);
    }
    

    So that using it in other contexts will look to be very much out of place, i.e.

    int *p=zero_value_to_foo{};
    

    This compiles, but leaves you with a dangling pointer; but hopefully the "zero_value_to_foo" label gives a honking clue that something is wrong here.

    Another little thing you can do to help yourself from misusing this is to use a ref qualifier for the operator:

    struct zero_value_to_foo {
        int v=0;
    
        operator int *() && { return &v; }
    };
    

    With this,

    foo(zero_value_to_foo{}, 0);
    

    still compiles, but not this:

    zero_value_to_foo zero{};
    
    foo(zero, 0);
    

    The more that can be done to make it difficult to use this except in the context is meant for, the fewer opportunities there are for bugs to creep by.

    0 讨论(0)
  • 2021-01-19 15:32

    I am assuming you want to pass a pointer to an integer 0, and not the 0 (NULL) pointer.

    If you don't mind allocating dynamic memory you can do this:

    func(new uint32_t(0), b);
    

    However, then you'd have to make sure to deallocate the memory inside the function.

    Alternatively, you can use an R-value references (c++11). Then you can use the address of the reference as the pointer inside your function.

    R-value reference syntax:

    uint32_t func(uint32_t &&a, uint32_t b);
    
    0 讨论(0)
提交回复
热议问题