我想在一个抽象类的std :: vector中存储从公共接口(抽象类)派生的类的对象.这个向量应该填充一个循环,通常我会调用类的构造函数并将创建的对象推送到向量中.
据我所知,在抽象类的情况下,我只能存储指向该类的指针,所以我需要push_back派生类的指针.但是,我不确定这些新创建的对象的范围.
请看下面的代码.这段代码编译并正常工作,但我的问题是:
a)对象是否保证存在于main函数的第二个for循环中?或者他们可能会停止存在超出创建它们的循环范围?
b)是否所有对象的析构函数都被调用或存在内存泄漏?
#include<vector>
#include<iostream>
class Interface {
public:
Interface( int y ) : x(y) {}
virtual ~Interface() {}
virtual void f() = 0;
int x;
};
class Derived_A : public Interface {
public:
Derived_A( int y ) : Interface(y) {}
void f(){ return; }
};
class Derived_B : public Interface {
public:
Derived_B( int y ) : Interface(y) {}
void f(){ return; }
};
int main()
{
std::vector<Interface*> abstractObjects;
int N = 5;
for(int ii …Run Code Online (Sandbox Code Playgroud) 我将std::unique_ptr对象的向量A作为参数传递给对象的构造函数Obj.当我使用std::move如下所示的语法时,这是有效的.但是,如果我将另一个对象添加到构造函数的参数列表(mpq_class i在下面的代码中),我会收到一条读取的错误消息
error: call to implicitly-deleted copy constructor of 'std::__1::unique_ptr<A, std::__1::default_delete<A> >'
Run Code Online (Sandbox Code Playgroud)
在OS X和
error: use of deleted function ‘std::unique_ptr<_Tp, _Dp>::unique_ptr(const std::unique_ptr<_Tp, _Dp>&) [with _Tp = Interface; _Dp = std::default_delete<Interface>]’
Run Code Online (Sandbox Code Playgroud)
在Linux系统上.
在函数中创建getVector()vector unique_ptr,然后传递给Obj构造函数,并将对象添加到另一个向量并返回.
我的问题是,如果我使用std::moveunique_ptrs以及如何摆脱它,代码会尝试调用复制构造函数!
产生错误的代码如下所示.
// g++ -Wall -O3 -std=c++1y -lgmpxx -lgmp
#include <vector>
#include <gmpxx.h>
#include <gmp.h>
#include <memory>
#include <iostream>
class A {
public:
A( int …Run Code Online (Sandbox Code Playgroud)