[英]Never provide destructor in the PIMPL(using boost scoped_ptr), the g++(4.6.1) doesn't generate compile error, Why?
After I read the reference link: Must provide destructor in the PIMPL , I do the follow the example, but the g++(4.6.1) doesn't generate compile error as I expected 在阅读参考链接之后: 必须在PIMPL中提供析构函数 ,我按照以下示例进行操作,但是g ++(4.6.1)不会产生预期的编译错误
The source code is: 源代码是:
// Predeclare.h
#include <vector>
#include <boost/scoped_ptr.hpp>
#include <iostream>
struct A;
class Predeclare
{
std::vector<A> alist_;
boost::scoped_ptr<A> pa_;
//A a;
public:
Predeclare();
//~Predeclare();
void print();
void set(int i);
};
// Predeclare.cpp
#include "Predeclare.h"
struct A
{
int a;
};
Predeclare::Predeclare(): pa_(new A)
{}
/*
Predeclare::~Predeclare()
{}
*/
void Predeclare::print()
{
std::cout << pa_->a << '\n';
}
void Predeclare::set(int i)
{
pa_->a = i;
}
int main()
{
Predeclare c1;
c1.set(10);
c1.print();
return 0;
}
Then, compile the program 然后,编译程序
g++ Predeclare.cpp
Everything is ok, Why the g++(4.6.1) doesn't generate compile error? 一切正常,为什么g ++(4.6.1)不会产生编译错误?
In your example, the compiler only needs a destructor for Predeclare
when it reaches the declaration of c1
in main()
. 在您的示例中,编译器在
main()
到达c1
Predeclare
时仅需要一个Predeclare
的析构函数。 By that point, A
has already been defined, earlier in Predeclare.cpp. 到那时,已经在Predeclare.cpp中定义了
A
If you were to try to instantiate Predeclare
in a different source file, you would likely run into problems. 如果要尝试在其他源文件中实例化
Predeclare
,则可能会遇到问题。
Note that instantiating std::vector<A>
where A
is incomplete yields undefined behavior. 请注意,实例化
std::vector<A>
其中A
不完整会产生未定义的行为。 When you instantiate a container, the value type must be Destructible, and only complete types are Destructible. 实例化容器时,值类型必须是可破坏的,而只有完整类型才是可破坏的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.