我想在所有者构造函数中调用成员对象的构造函数,但由于依赖关系,无法在初始化器列表中构造成员对象。如何在初始化后调用构造器?我真的不想使用init方法
发布于 2018-07-13 15:55:17
No。
不能在初始值设定项列表之外调用成员类的构造函数。
PS:即使你没有在初始化器列表中自己调用它,编译器也会隐式地调用它。
如果您不能在初始化器列表中调用它,并且您不想使用类似init的方法,那么请重新考虑您的设计/方法。
发布于 2018-07-13 16:37:31
您有两个选择:使用动态存储或放置新的。
第一个是显而易见的(正如评论中指出的,您可以使用unique_ptr)。如果您想避免这种情况,您可以尝试使用std::aligned_union作为存储来放置新的内容:
class SomeClass { ... };
class Owner
{
public:
Owner()
{
m_ptr = new(&m_storage) SomeClass();
}
~Owner()
{
m_ptr->~SomeClass();
}
private:
std::aligned_union<0, SomeClass> m_storage;
SomeClass* m_ptr;
};注意:在这种情况下,你需要负责调用对象的析构函数,如上所示。
你可以用一个unique_ptr来包装m_ptr (使用一个只调用析构函数的deleted )来避免这种情况:
struct DtorDeleter
{
template<typename T>
void operator ()(T* ptr) { ptr->~T(); }
};
std::unique_ptr<SomeClass, DtorDeleter> m_ptr; // no need to call destructor manually发布于 2018-07-13 16:53:02
您可以为此使用联合(需要C++11):
#include <new>
class Foo {
public:
Foo(int a) { }
};
class Bar {
public:
Bar() {
new(&m_foo) Foo(42); // call the constructor
// you can use m_foo from this point
}
~Bar() {
m_foo.~Foo(); // call the destructor
}
private:
union { // anonymous union
Foo m_foo;
};
};请注意,您需要在~Bar()显式调用m_foo的析构函数。
https://stackoverflow.com/questions/51320238
复制相似问题