我被告知,在C++ 03中,临时性是隐含的不可修改的.
但是,以下为GCC 4.3.4编译(在C++ 03模式下):
cout << static_cast<stringstream&>(stringstream() << 3).str();
Run Code Online (Sandbox Code Playgroud)
这是怎么编译的?
(我不是在谈论有关临时引用的临时规则.)
我偶然发现了以下代码,并想知道它的优点
std::string const & thestring( "XYZ" );
Run Code Online (Sandbox Code Playgroud)
事实上,它正在构建对象并通过引用引用它.我以前常常看到
std::string const theString( "XYZ" );
Run Code Online (Sandbox Code Playgroud)
并且想知道差异是什么.我很高兴对象不会被早期破坏,因为对象与引用一起存在于堆栈中.
在我正在编写的程序中出现了以下模式.我希望它不是太做作,但它设法Foo在const方法中改变一个对象Foo::Questionable() const,而不使用任何const_cast或类似的东西.基本上,Foo存储参考FooOwner,反之亦然,并在Questionable(),Foo设法修改本身在一个const方法通过调用mutate_foo()关于它的主人.问题遵循代码.
#include "stdafx.h"
#include <iostream>
using namespace std;
class FooOwner;
class Foo {
FooOwner& owner;
int data;
public:
Foo(FooOwner& owner_, int data_)
: owner(owner_),
data(data_)
{
}
void SetData(int data_)
{
data = data_;
}
int Questionable() const; // defined after FooOwner
};
class FooOwner {
Foo* pFoo;
public:
FooOwner()
: pFoo(NULL)
{}
void own(Foo& foo)
{
pFoo = &foo;
}
void mutate_foo()
{
if …Run Code Online (Sandbox Code Playgroud) 这是最近出现的事情,我觉得它显然不应该起作用:
#include <iostream>
#include <memory>
int main()
{
std::shared_ptr<int>& ptr = const_cast<std::shared_ptr<int>&>(
static_cast<const std::shared_ptr<int>&>(
std::shared_ptr<int>(
new int(5), [](int* p) {std::cout << "Deleting!"; *p = 999; delete(p); }
)
)
);
std::cout << "I'm using a non-const ref to a temp! " << *ptr << " ";
}
Run Code Online (Sandbox Code Playgroud)
shared_ptr此处不需要使用,但自定义删除器允许轻松演示结果对象的生命周期。Visual Studio、Clang 和 GCC 的结果输出是相同的:
我正在使用非常量引用来表示临时值!5 删除!
这意味着结果的生命周期shared_ptr已通过某种机制扩展到匹配std::shared_ptr<int>& ptr.
现在,我知道在常量引用的情况下,临时对象的生命周期将扩展到引用的生命周期。但是唯一的命名对象是非常量引用,我希望所有其他中间表示的生命周期仅等于初始化表达式。
此外,Microsoft 有一个扩展,它允许非常量引用延长绑定临时的生命周期,但即使禁用该扩展,这种行为似乎也存在,此外,也出现在 Clang 和 GCC 中。
根据这个答案,我相信临时对象被隐式创建为const,因此尝试修改引用的对象ptr可能是未定义的行为,但我不确定这些知识是否告诉我有关为什么延长生命周期的任何信息。我的理解是,这是修改UB 的 const的行为,而不是简单地对它进行非常量引用。 …