爲了阻止論點的an answer I gave recently評論的時候,我想了一些建設性的回答以下問題:就其目標參考的壽命
- 是一個參考的生命週期不同從它指的對象?參考只是其目標的別名嗎?
- 參考文獻能否在一個格式良好的程序中超越其目標而不會導致未定義的行爲?
- 如果爲原始對象分配的存儲空間被重用,是否可以引用新對象?
- 下面的代碼是否演示了上述幾點而未調用未定義的行爲?
實施例的代碼由Ben Voigt和簡化(上ideone.com運行它):
#include <iostream>
#include <new>
struct something
{
int i;
};
int main(void)
{
char buffer[sizeof (something) + 40];
something* p = new (buffer) something;
p->i = 11;
int& outlives = p->i;
std::cout << outlives << "\n";
p->~something(); // p->i dies with its parent object
new (p) char[40]; // memory is reused, lifetime of *p (and p->i) is so done
new (&outlives) int(13);
std::cout << outlives << "\n"; // but reference is still alive and well
// and useful, because strict aliasing was respected
}
這是一大堆問題,每個問題都需要相當一些標準的措詞引用才能正確回答(鑑於問題的性質,我認爲您期望標準引用是正確答案)。如果我們應該專注於其中的一個,它/可能會更有用,如果在這方面有用,只回答其他人... – PlasmaHH 2012-02-15 10:15:14
我同意。請問每個問題有一個問題。你會發現以前的子問題已經回答了。 – 2012-02-15 10:24:10
此外,該代碼示例還有很多事情要做。製作一個小型測試用例。 – 2012-02-15 10:24:28