嵌套 class 在具有 C++ 智能指针的成员函数中构造
Nested class constructed in a member function with smart pointers in c++
我有以下简单代码
class Hybrid{
std::unique_ptr<Bcf> bndfac;
void constructbndFace( const int &nn){
bndfac( new Bcf(nn) ); // Does not work (A)
//std::unique_ptr<Bcf> bndfac( new Bcf(nn) ); // WORKS (B)
}
}
class Bcf{
Bcf(const int nn_) : nn(nn_){}
private:
int nn;
}
当我尝试调用 Hybrid::constructbndFace
时,我不明白为什么编译器会抱怨 std::unique_ptr< Bcf >' does not provide a call operator
。如果我使用注释行 (B),编译器将不再报错。
我的问题是,如果我使用 (B) 行,实例化的对象是否可以通过我在 Hybrid 中的声明进行访问 class,或者我是否做错了什么 Hybrid->bndFace
在 B 行中,您创建了一个临时对象,其名称隐藏了成员名称。然后它在下一行用右曲括号销毁。
如果你想构造 bndfac 对象,你应该用这个替换你的 B 行:
bndfac = std::make_unique<Bcf>(nn);
我有以下简单代码
class Hybrid{
std::unique_ptr<Bcf> bndfac;
void constructbndFace( const int &nn){
bndfac( new Bcf(nn) ); // Does not work (A)
//std::unique_ptr<Bcf> bndfac( new Bcf(nn) ); // WORKS (B)
}
}
class Bcf{
Bcf(const int nn_) : nn(nn_){}
private:
int nn;
}
当我尝试调用 Hybrid::constructbndFace
时,我不明白为什么编译器会抱怨 std::unique_ptr< Bcf >' does not provide a call operator
。如果我使用注释行 (B),编译器将不再报错。
我的问题是,如果我使用 (B) 行,实例化的对象是否可以通过我在 Hybrid 中的声明进行访问 class,或者我是否做错了什么 Hybrid->bndFace
在 B 行中,您创建了一个临时对象,其名称隐藏了成员名称。然后它在下一行用右曲括号销毁。
如果你想构造 bndfac 对象,你应该用这个替换你的 B 行:
bndfac = std::make_unique<Bcf>(nn);