dav*_*vka 5 c++ constructor const-reference temporary-objects
通过一个例子更好地解释:
tok.h
#include <string>
static const char* defaultDelim = ".,;";
class Tokenizer {
public:
Tokenizer():
// 'delim' is the const ref member that is initialized by the temp string
delim( (altDelim.size())? altDelim : std::string(defaultDelim) )
{}
size_t scan(const std::string& str)
{ return str.find_first_of(delim); }
static void setDelim(const std::string& d) { altDelim = d; }
private:
static std::string altDelim;
const std::string& delim;
};
Run Code Online (Sandbox Code Playgroud)
main.cpp中
#include <iostream>
using namespace std;
#include "tok.h"
std::string Tokenizer::altDelim;
int main()
{
Tokenizer tok;
size_t pos = tok.scan("hello, world");
cout << pos << endl;
}
Run Code Online (Sandbox Code Playgroud)
程序打印0这是错误的.真正的代码会出现seg错误.
我期望延长分配给const引用的temp的寿命的规则将在这里保留,但显然它不是.你知道原因吗?
该规则不适用于班级成员。C++03 标准的 12.2.5 中对此进行了说明:
A temporary bound to a reference member in a constructor's ctor-initializer
persists until the constructor exits.
Run Code Online (Sandbox Code Playgroud)
使临时对象的持续时间比这更长意味着必须将临时对象保留为类的一部分,以便维持其生命周期。如果构造函数位于单独的编译单元中,这是不可能的,因为在定义类时必须知道类的大小。
// header file
struct A {
A();
B &b;
};
// file1.cpp
void f()
{
A a; // Reserve the size of a single reference on the stack.
}
// file2.cpp
A::A()
: b(B()) // b is referencing a temporary, but where do we keep it?
// can't keep the temporary on the stack because the
// constructor will return and pop everything off the stack.
// Can't keep it in the class because we've already said the
// class just contains a single reference.
{
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
295 次 |
| 最近记录: |