对于水母精华区里多次讲到的T t = v;的实际过程,这里(叫做explicit initialization)有很明确的解释:
其中一个之前没有注意到的问题是,尽管编译器可以将2步优化为1步,但要求copy ctor必须为public的,否则就会失败。
Even if, as in the above example, the compiler does not generate a call to the copy constructor, it must be available. This is illustrated in the following program (available as test-2.C) which does not compile.
#include
class T {
public:
T(int i): data_(i) { std::cerr << "T::T(int)" <<>
private:
T(const T&) { std::cerr << "T::T(const T&)" <<>
int data_;
};
int main(int, char**) {
T t1(3); // OK
T t2 = 3; // Error: T::T(const T&) private.
}
For the above program, the compiler issues the following error message
test-2.C: In function `int main(int, char**)':
test-2.C:6: `T::T(const T&)' is private
test-2.C:13: within this context
test-2.C:13: initializing temporary from result of `T::T(int)'

没有评论:
发表评论