use*_*932 4 c++ auto-ptr visual-studio-2010 visual-c++
我有一个基类,它由多个派生类继承.我想创建baseClass指针的autopointer数组.当我初始化那些autopointer我得到一些编译时错误,然后我试图这样做
std::auto_ptr<base>pbase[3];
std::auto_ptr<base> b1(new derived1());
std::auto_ptr<base> b2(new derived2());
std::suto_ptr<base> b3(new derived3());
pbase[0] = b1;
pbase[1] = b2;
pbase[2] = b3;
Run Code Online (Sandbox Code Playgroud)
它工作正常,我修复了内存泄漏问题,而我一个窗口,我不使用valgrind,我使用boost框架泄漏.
编译错误:
class A{
public:
std::auto_ptr<base>pbase[2];
}
Run Code Online (Sandbox Code Playgroud)
在A.cpp文件中
A::A():pbase[0](new derived1()), pbase[1](new derived2()){
}
Run Code Online (Sandbox Code Playgroud)
我收到了错误 C2059:syntax error : '['
std::auto_ptr 自C++ 11以来已弃用,因其奇怪的复制行为而不应使用:
std::auto_ptr<int> a(new int(1));
std::auto_ptr<int> b = a; // invalidates a!
Run Code Online (Sandbox Code Playgroud)
它试图实现的目标现在已经彻底解决了std::unique_ptr.在引入移动语义和右值引用之前,这是不可能的.
但是,这似乎不是问题所在.从您的示例中,您可能会因为调用未定义的行为而泄漏内存:
pbase[3] = b3; // pbase is std::auto_ptr<base>[3]
// pbase[0] - pbase[2] are valid indexes
Run Code Online (Sandbox Code Playgroud)
事实上,当我解决问题并运行valgrind --leak-check=full ./auto_ptr_app结果时,它告诉我没有泄漏是可能的.