我正在尝试将不可复制(但可移动)的对象存储在 std::pair 中,如下所示:
#include <utility>
struct S
{
S();
private:
S(const S&);
S& operator=(const S&);
};
int main()
{
std::pair<int, S> p{0, S()};
return 0;
}
但是我在使用 gcc 4.6 时遇到以下编译器错误:
In file included from include/c++/4.6.0/bits/move.h:53:0,
from include/c++/4.6.0/bits/stl_pair.h:60,
include/c++/4.6.0/utility:71,
from src/test.cpp:1:
include/c++/4.6.0/type_traits: In instantiation of 'const bool std::__is_convertible_helper<S, S, false>::__value':
include/c++/4.6.0/type_traits:789:12: instantiated from 'std::is_convertible<S, S>'
src/test.cpp:13:31: instantiated from here
src/test.cpp:7:5: error: 'S::S(const S&)' is private
include/c++/4.6.0/type_traits:782:68: error: within this context
In file included from include/c++/4.6.0/utility:71:0,
from src/test.cpp:1:
src/test.cpp: In constructor 'std::pair<_T1, _T2>::pair(_U1&&, const _T2&) [with _U1 = int, <template-parameter-2-2> = void, _T1 = int, _T2 = S]':
src/test.cpp:13:31: instantiated from here
src/test.cpp:7:5: error: 'S::S(const S&)' is private
include/c++/4.6.0/bits/stl_pair.h:121:45: error: within this context
似乎编译器正在尝试调用std::pair<_T1, _T2>::pair(_U1&&, const _T2&)
构造函数,这当然是有问题的。编译器不应该调用std::pair<_T1, _T2>::pair(_U1&&, _U2&&)
构造函数吗?这里发生了什么?
编辑:好的,我知道提供显式移动构造函数可以解决问题,但我还是有点困惑。
假设我通过继承boost::noncopyable
而不是声明我自己的私有复制构造函数来使类不可复制。
以下工作正常,表明隐式生成了移动构造函数:
#include <boost/noncopyable.hpp>
struct S : boost::noncopyable
{
};
void f(S&&)
{
}
int main()
{
f(S());
return 0;
}
但是,std::pair
它仍然不起作用:
#include <utility>
#include <boost/noncopyable.hpp>
struct S : boost::noncopyable
{
};
int main()
{
std::pair<int, S> p{0, S()};
return 0;
}
错误:
In file included from include/c++/4.6.0/utility:71:0,
from src/test.cpp:1:
/include/c++/4.6.0/bits/stl_pair.h: In constructor 'std::pair<_T1, _T2>::pair(_U1&&, const _T2&) [with _U1 = int, <template-parameter-2-2> = void, _T1 = int, _T2 = S]':
src/test.cpp:16:31: instantiated from here
/include/c++/4.6.0/bits/stl_pair.h:121:45: error: use of deleted function 'S::S(const S&)'
src/test.cpp:4:8: error: 'S::S(const S&)' is implicitly deleted because the default definition would be ill-formed:
boost/boost/noncopyable.hpp:27:7: error: 'boost::noncopyable_::noncopyable::noncopyable(const boost::noncopyable_::noncopyable&)' is private
src/test.cpp:4:8: error: within this context
此外,添加= default
-ed 默认构造函数和移动构造函数也无济于事!
#include <utility>
#include <boost/noncopyable.hpp>
struct S : boost::noncopyable
{
S() = default;
S(S&&) = default;
};
int main()
{
std::pair<int, S> p{0, S()};
return 0;
}
我得到同样的错误!我必须自己明确给出移动构造函数的定义,如果类有很多成员,这很烦人:
#include <utility>
#include <boost/noncopyable.hpp>
struct S : boost::noncopyable
{
S() = default;
S(S&&) {}
};
int main()
{
std::pair<int, S> p{0, S()};
return 0;
}