为什么这样:
#include <string>
#include <iostream>
using namespace std;
class Sandbox
{
public:
Sandbox(const string& n) : member(n) {}
const string& member;
};
int main()
{
Sandbox sandbox(string("four"));
cout << "The answer is: " << sandbox.member << endl;
return 0;
}
Run Code Online (Sandbox Code Playgroud)
给出输出:
答案是:
代替:
答案是:四
我理解如果临时绑定到构造函数的初始化列表中的引用成员,则该对象将在构造函数返回时被销毁.
但是,请考虑以下代码:
#include <functional>
#include <iostream>
using callback_func = std::function<int(void)>;
int
func(const callback_func& callback)
{
struct wrapper
{
const callback_func& w_cb;
wrapper(const callback_func& cb) : w_cb {cb} { }
int call() { return this->w_cb() + this->w_cb(); }
};
wrapper wrp {callback};
return wrp.call();
}
int
main()
{
std::cout << func([](){ return 21; }) << std::endl;
return 0;
}
Run Code Online (Sandbox Code Playgroud)
这看起来对我来说完全有效.该callback对象将在整个func函数执行期间生效,并且不应为其wrapper构造函数创建临时副本.
实际上,GCC 4.9.0在启用所有警告的情况下编译正常.
但是,GCC 4.8.2编译器给了我以下警告:
$ g++ -std=c++11 -W …Run Code Online (Sandbox Code Playgroud) 我目前正在尝试理解C++ 0x的新统一初始化.不幸的是,我对使用引用的统一初始化感到困惑.例:
int main() {
int a;
int &ref{a};
}
Run Code Online (Sandbox Code Playgroud)
这个例子工作正常:
% LANG=C g++ uniform_init_of_ref.cpp -std=c++0x -o uni -Wall -Wextra
uniform_init_of_ref.cpp: In function `int main()':
uniform_init_of_ref.cpp:3:10: warning: unused variable `ref' [-Wunused-variable]
Run Code Online (Sandbox Code Playgroud)
(更新 Comeau会为该示例抛出错误,因此gcc也不应该编译它)
现在,如果我使用自定义数据类型而不是整数,它将不再起作用:
class Y
{};
int main()
{
Y y;
Y &ref{y};
}
% LANG=C g++ initialization.cpp -std=c++0x -o initialization -Wall -Wextra
initialization.cpp: In function `int main()':
initialization.cpp:9:13: error: invalid initialization of non-const reference of type `Y&' from an rvalue of type `<brace-enclosed initializer list>'
initialization.cpp:9:8: warning: …Run Code Online (Sandbox Code Playgroud)