比如我有一个类
struct A
{
A(int i, double d) {...}
};
和一个带有参数 A 的函数
void f(A a);
我可以调用这个函数
f( { 1, 3.14 } );
如果函数有一个参数A*
void g(A* a);
如何让它调用起来
g( my_new{1, 3.14} ); // Note: no type A is shown here.
或者这里的类型A怎么推导出来?
最佳答案
你不能“直接”获取一个临时地址...
你不能用&
获取临时地址:
g(&({1, 3.14}));
根据:
§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.
(强调我的)
...但你可以间接地!
例如,您可以使用一个函数来提取指向临时对象的指针:
A* fn(A&& a) {
return std::addressof(a);
}
并将其用作:
g(fn({1, 4.0}));
请注意,std::addressof
是避免类 A
可能的 operator&
重载所必需的。
您还可以通过 A
类的成员函数以及可能的许多其他方式提取它。
为什么观点突然改变?好吧,我已经discussed it与其他 C++ 仇恨者一起,显然这是可能的并且完全合法。
我的建议
我建议 g
使用 const
引用:
void g(const A& a);
然后:
g({1, 3.14});
将正常工作(当然,假设构造函数不是显式的)。
关于c++ - 如何对指针使用统一初始化?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24411638/