考虑以下程序:
#include <iostream>
#include <utility>
class T {
public:
T() { printf("address at construction: %zx\n", (uintptr_t)this); }
// T(const T&) { printf("copy-constructed\n"); } // helps
// T(T&&) { printf("move-constructed\n"); } // helps
// T(const T&) = default; // does not help
// T(T&&) = default; // does not help
};
T f() { return T(); }
int main() {
T x = f();
printf("address after construction: %zx\n", (uintptr_t)&x);
return 0;
}
用。编译 g++ -std=c++17 test.cpp
给出以下输出(与...相同) clang++
):
address at construction: 7ffcc7626857
address after construction: 7ffcc7626887
基于 C ++参考 我希望程序输出两个相同的地址,因为应该保证复制/移动被省略(至少在C ++ 17中)。
如果我显式定义了复制或移动构造函数或两者(参见示例中注释掉的行),程序会给出预期的输出(即使使用C ++ 11):
address at construction: 7ffff4be4547
address after construction: 7ffff4be4547
只需将复制/移动构造函数设置为 default
没有帮助。
该引用明确指出
[复制/移动构造函数]不需要存在或可访问
那我在这里错过了什么?