【发布时间】:2012-01-08 16:37:19
【问题描述】:
#include "stdafx.h"
class Base
{
public:
Base(){}
virtual ~Base(){}
private:
Base(const Base &other) ; // Only declaration! No definition.
Base &operator=(const Base &other);
} ;
int _tmain(int argc, _TCHAR* argv[])
{
const Base b ; // ok
const Base *pb = &Base() ; // ok
const Base &qb = Base() ; // Illegal, why?
return 0;
}
然后,看下面的代码:
#include "stdafx.h"
class Base
{
public:
Base(){}
virtual ~Base(){}
public:
Base(const Base &other) ; // Only declaration! No definition.
Base &operator=(const Base &other);
} ;
int _tmain(int argc, _TCHAR* argv[])
{
const Base b ; // ok
const Base *pb = &Base() ; // ok
const Base &qb = Base() ; // It's ok! why?
return 0;
}
【问题讨论】:
-
您应该添加更多文字来解释您要查找的内容。
-
请注意,
const Base *pb = &Base()不 ok,应该从编译器发出警告 -
这个
const Base *pb = &Base() ;绝对不 OK。这是一个微软扩展。 -
const Base &bp = Base();涉及对临时对象的引用的生命周期延长(第 12.2 节临时对象) -
@ybungalobill 这不是 Microsoft 扩展。 GCC 和标准也允许它。但是,它仍然是使程序崩溃的好方法。
标签: c++ constants variable-assignment language-lawyer copy-constructor