赋值bsoncxx::builder::basic::document触发E1776错误的原因及解决
问题分析与解决方案
错误原因
bsoncxx::builder::basic::document是不可拷贝的类型,它的拷贝赋值运算符被隐式删除(类内部包含不可拷贝的成员),直接通过=进行拷贝赋值的操作不合法,这就是触发E1776错误的核心原因。这类builder对象设计时就不支持拷贝,因为它们内部管理着动态分配的BSON结构资源。
解决方案
以下几种可行方式,可根据你的使用场景选择:
1. 使用文档视图追加内容
通过view()方法获取已有文档的只读视图,再用append()方法把内容追加到full_query中,这是最安全的方式,不会影响原文档对象:
auto full_query = bsoncxx::builder::basic::document{}; if (these && those) { full_query.append(kvp("$and", make_array(these_guys.view(), those_guys.view()))); } else if (these) { full_query.append(these_guys.view()); } else if (those) { full_query.append(those_guys.view()); }
2. 使用移动语义转移所有权
如果后续不再需要使用these_guys或those_guys,可以用std::move()触发移动赋值,转移对象的资源所有权:
auto full_query = bsoncxx::builder::basic::document{}; if (these && those) { full_query.append(kvp("$and", make_array(std::move(these_guys), std::move(those_guys)))); } else if (these) { full_query = std::move(these_guys); } else if (those) { full_query = std::move(those_guys); }
注意:移动后原文档对象these_guys/those_guys会处于有效但未定义的状态,不能再对其执行任何操作。
3. 直接在分支中构建full_query
避免提前创建空文档,而是在对应分支里直接初始化full_query:
bsoncxx::builder::basic::document full_query; if (these && those) { full_query.append(kvp("$and", make_array(these_guys.view(), those_guys.view()))); } else if (these) { full_query = bsoncxx::builder::basic::document{}; full_query.append(kvp("Name", "Smith")); } else if (those) { full_query = bsoncxx::builder::basic::document{}; full_query.append(kvp("Name", "Jones")); }
这种方式适合原文档对象逻辑简单的场景,避免额外的视图或移动操作。
内容的提问来源于stack exchange,提问作者PeterT
相关产品推荐
相关产品推荐

