在急速的时刻,需要一个指向对象的指针传递给一个函数.我拿了一个未命名的临时对象的地址,令我惊讶的是它编译了(原始代码的警告进一步向下,缺少下面例子中的const正确性).好奇,我设置了一个受控制的环境,一直有警告,并将警告视为Visual Studio 2013中的错误.
请考虑以下代码:
class Contrived {
int something;
};
int main() {
const Contrived &r = Contrived(); // this is well defined even in C++03, the object lives until r goes out of scope
const Contrived *p1 = &r; // compiles fine, given the type of r this should be fine. But is it considering r was initialized with an rvalue?
const Contrived *p2 = &(const Contrived&)Contrived(); // this is handy when calling functions, is it valid? It also compiles
const int *p3 = &(const int&)27; // it works with PODs too, is it valid C++?
return 0;
}
Run Code Online (Sandbox Code Playgroud)
三个指针初始化或多或少都是一样的.问题是,这些初始化是在C++ 03,C++ 11或两者下有效的C++吗?考虑到rvalue引用周围的大量工作,我会分别考虑C++ 11以防万一.分配这些值可能似乎不值得,例如在上面的示例中,但是值得注意的是,如果将这些值传递给采用常量指针的函数并且没有适当的对象,或者感觉不到比如在上面一行上制作一个临时对象.
编辑:
根据答案,上述是有效的C++ 03和C++ 11.关于最终对象的生命周期,我想提出一些额外的澄清要点.
请考虑以下代码:
class Contrived {
int something;
} globalClass;
int globalPOD = 0;
template <typename T>
void SetGlobal(const T *p, T &global) {
global = *p;
}
int main() {
const int *p1 = &(const int&)27;
SetGlobal<int>(p1, globalPOD); // does *p still exist at the point of this call?
SetGlobal<int>(&(const int&)27, globalPOD); // since the rvalue expression is cast to a reference at the call site does *p exist within SetGlobal
// or similarly with a class
const Contrived *p2 = &(const Contrived&)Contrived();
SetGlobal<Contrived>(p2, globalClass);
SetGlobal<Contrived>(&(const Contrived&)Contrived(), globalClass);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
问题是对SetGlobal的调用中的一个或两个是否有效,因为它们传递的指针指向在C++ 03或C++ 11标准下调用期间将存在的对象?
An rvalue是一种表达式,而不是一种对象.我们在谈论创建的临时对象Contrived(),说"这个对象是一个右值"是没有意义的.创建对象的表达式是rvalue表达式,但这是不同的.
即使所讨论的对象是临时对象,其寿命也已延长.使用r表示它的标识符对对象执行操作是完全正确的.表达式r是左值.
p1没关系 在p2和p3行上,引用的生命周期在该完整表达式的末尾结束,因此临时对象的生命周期也在该点结束.因此,使用p2或p3后续行将是未定义的行为.初始化表达式可以用作函数调用的参数,如果这是你的意思.