G++ 4.9.3 抱怨好友 ctor 是私有的 .emplace_back(),但喜欢 .push_back()
g++ 4.9.3 complains that friended ctor is private with .emplace_back(), but likes .push_back()
我一定错过了关于emplace()和朋友的一个细节。下面是一个完整的最小示例,重现了 g++ 4.9.3 的问题:
class Foo
{
public:
class Bar
{
private:
friend class Foo;
Bar(Foo &foo) : foo(foo) {}
Foo &foo;
};
Bar &getBar()
{
//bars.push_back(*this); // works fine
bars.emplace_back(*this); // Foo::Bar::Bar(Foo&) is private
return bars.back();
}
private:
std::vector<Bar> bars;
};
在emplace_back
中,容器是构造Bar
的容器。但是该构造函数是私有的,容器不是友元,因此它会失败。
但push_back(*this)
相当于push_back(Bar(*this))
.也就是说,是Foo
在做建设,它是朋友。
bars.emplace_back(*this);
延迟对构造函数的调用Bar(Foo&)
std::vector::emplace_back()
。该函数没有调用Bar(Foo&)
的访问权限。
另一方面
bars.push_back(*this);
在调用 std::vector::push_back()
之前调用构造函数Bar(Foo&)
。这不是问题,因为Foo
是Bar
friend
。
相关文章:
- TMap::Emplace() 在应用现有密钥时会覆盖吗?
- 推导 std::vector::back() 的返回类型
- 为什么 C++ std::unordered_map 从 emplace/ 找到返回一个迭代器?
- vector.back() 和 vector[vector.size() - 1] 之间的区别?
- 将 std::map::emplace 与返回 shared_ptr 的函数一起使用是否正确?
- vector.push_back(vector.back()+1) 是未定义的行为吗?
- 不为 emplace() 定义构造函数的解决方法
- 如何提取由 unordered_map::emplace 重新调整的货币对的值?
- 如何最好地将 emplace 与 std::map 一起使用
- 线路抑制状态错误 C4703 可能未初始化的局部指针变量"back"已使用
- std::vector using back(), pop_back(), push_back(), 得到'double free or corruption'错误
- std::vector::emplace() 真的在面对抛出移动构造函数/赋值运算符时提供了强大的异常保证吗?
- std::map::emplace无法解决,但插入右值有效 - 为什么?
- vector.back()和vector.end()有什么区别
- 为什么 std::map emplace 需要在 gcc 上有一个复制构造函数
- 为什么unordered_map的 emplace piecewise_construct参数需要默认构造函数?
- std::元组到元组的映射和使用 emplace
- 列表大小为 1,但 front() 和 back() 不相等
- 如何使用 emplace 添加到C++中的地图
- C++ map emplace