Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use uniform initialization for a pointer?

For example, I have a class

struct A
{
    A(int i, double d) {...}
};

and a function with an argument A

void f(A a);

I can call the function by

f( { 1, 3.14 } );

If the function has an argument A*

void g(A* a);

How to make it call like

g( my_new{1, 3.14} ); // Note: no type A is shown here.

Or how to derive the type A here?

like image 203
user1899020 Avatar asked Dec 03 '25 01:12

user1899020


1 Answers

You can't take an address of a temporary "directly"...

You can't take an address of a temporary with &:

g(&({1, 3.14})); 

as per:

§5.3.1/3

The result of the unary & operator is a pointer to its operand. The operand shall be an lvalue or a qualified-id.

(emphasis mine)

... but you can indirectly!

For example, you can use a function to extract the pointer to the temporary object:

A* fn(A&& a) {
    return std::addressof(a);
}

and use it as:

g(fn({1, 4.0}));

Note that std::addressof is necessary to avoid possible operator& overloading for the class A. You could also extract it via a member function of the class A and probably many other ways.

Why the sudden opinion change? Well, I've discussed it with other C++ haters and apparently it is possible and perfectly legal.

What I'd recommend

I'd recommend for g to take a const reference instead:

void g(const A& a);

and then:

g({1, 3.14});

will work fine (assuming, of course, that the constructor is not explicit).

like image 113
Shoe Avatar answered Dec 05 '25 15:12

Shoe



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!