【发布时间】:2017-08-26 19:41:21
【问题描述】:
知道为什么这不能编译:
#include <iostream>
#include <vector>
class A {
public:
A() : m_Member( 1 ) {
std::cout << "Constructor called." << std::endl;
}
A( A const & t_a ) {
m_Member = t_a.m_Member;
std::cout << "Copy constructor called." << std::endl;
}
virtual ~A() {
std::cout << "Destructor called." << std::endl;
m_Member = 0;
}
void play() { std::cout << "Number is: " << m_Member << std::endl; }
private:
int m_Member;
};
class B {
public:
B() {
std::cout << "Main object created!" << std::endl;
}
B( B & b ) {
for( std::unique_ptr< A >& val: b.m_Array ) {
m_Array.push_back( std::unique_ptr< A >( new A( *val ) ) );
}
}
virtual ~B() {
std::cout << "Main object destroyed!" << std::endl;
}
A& get( size_t const Index ) {
return *m_Array[ Index ];
}
void add( A& a ) {
m_Array.push_back( std::unique_ptr< A >( new A( a ) ) );
}
private:
std::vector< std::unique_ptr< A > > m_Array;
};
B createB() {
B b;
A a1;
A a2;
b.add( a1 );
b.add( a2 );
return b;
}
int main() {
B b = createB();
A& temp = b.get( 1 );
temp.play();
return 0;
}
我明白了:
错误:没有匹配的构造函数用于初始化 'B' B b = createB();
另外,对于这个例子,有没有更好的方法来保存对象的向量?请注意,我故意在函数中创建对象,以便在销毁 B 之前删除传递给类 B 的对象。在这种情况下,引用包装器不起作用,因为它指向已被删除的对象。我试图通过引入 unique_ptr 来解决这个问题,但是我得到了这个错误。
【问题讨论】:
标签: c++ c++11 smart-pointers stdvector unique-ptr