Tom*_*Tom 0 c++ struct reference constants
我遇到了一个问题,而试图分配struct与const&成员的地图。
struct test {
const int& number;
test(const int& cnumber) : number(cnumber) {}
test(const test&) = default;
test& operator=(const test&) = default;
};
Run Code Online (Sandbox Code Playgroud)
int main () {
std::map<std::string, test> testmap;
testmap["asd"] = test(2);
}
Run Code Online (Sandbox Code Playgroud)
运行此代码会导致错误 C2280 'test &test::operator =(const test &)': attempting to reference a deleted function
谁能向我解释这里的问题是什么?这是一个最小的可重现示例。在我的实际项目中,数据要大得多,因此按值传递是不明智的。
引用不可分配。因此,operator =编译器提供的默认值被隐式删除。即使你有
test& operator=(const test&) = default;
Run Code Online (Sandbox Code Playgroud)
operator =这里的“默认”是一个被删除的运算符,所以你仍然没有一个。您要么不需要使用引用,要么编写自己的引用来满足operator =您的需求。
| 归档时间: |
|
| 查看次数: |
57 次 |
| 最近记录: |