【发布时间】:2014-05-03 01:07:50
【问题描述】:
匆忙中,需要一个指向对象的指针来传递给函数。我获取了一个未命名的临时对象的地址,令我惊讶的是它编译了(原始代码的警告被进一步降低,并且缺乏下面示例中存在的 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;
}
三个指针初始化或多或少都是一回事。问题是,这些初始化在 C++03、C++11 或两者下是有效的 C++ 吗?考虑到围绕右值引用进行了大量工作,我会单独询问 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;
}
问题是对 SetGlobal 的调用中的一个或两个是否有效,因为它们传递了一个指向在 C++03 或 C++11 标准下调用期间将存在的对象的指针?
【问题讨论】: