【发布时间】:2017-11-23 14:51:06
【问题描述】:
我有一个现有的功能:
void foo(const Key* key = nullptr)
{
// uses the key
}
我想将它的指针传递给临时 Key 对象(即右值),例如:
foo(&Key());
这会导致编译错误,但是在 c++ 11/14 中有没有办法我可以做到这一点?当然可以:
Key key;
foo(&key);
但是我不需要object Key,我只需要在foo()和foo()里面
或者我可以这样做:
foo(new Key());
但随后对象不会被删除。
【问题讨论】:
-
添加
void foo(const Key &key){ foo(&key); }怎么样? -
您是否同时使用了
c++的三种不同标准? -
@Detonar 我认为没有必要在其中引入动态分配。
-
@AndreyRubliov:因为它不是自然的,也不应该是自然的。
-
@AndreyRubliov:不自然的是将指针传递给临时对象。
标签: c++ c++11 c++14 c++17 temporary-objects