mirror of
https://github.com/Light-City/CPlusPlusThings.git
synced 2026-10-28 19:04:45 +08:00
- const README: rewrite the space-saving claim per issue #5 follow-ups (constant-expression const vs #define immediates; which const qualify as constant expressions) - const README: fix the class-section diagnosis per issue #338 (overload resolution picks the const overload; the restriction only surfaces once that overload is removed) - sizeof README: virtual-inheritance result is compiler-dependent (GCC merges vbptr+vfptr -> 16, MSVC keeps them separate -> 32) #246 - static README: new section on internal linkage / access restriction with anonymous-namespace comparison #142 - 10-day practice: full problem list table + fixed day links #136 - new design_pattern/singleton/singleton_default.hpp: reusable thread-safe CRTP singleton template, compile+concurrency tested #303
2.1 KiB
2.1 KiB
来自 C++那些事网站 的文章,由站点同步脚本导出。
C++ 成员初始化列表注意点
在C++中,类的正确初始化是确保程序正常运行的关键步骤之一。尤其是在使用初始化列表时,我们需要注意一些潜在的陷阱,以避免在代码执行过程中产生意外的结果。
初始化列表通常被认为是设置新类实例状态的首选方法,因为它提供了一种简洁、高效的方式来初始化类成员。然而,有时候在初始化列表中引用其他成员变量可能导致一些令人困惑的问题。
问题示例
考虑以下的Foo类:
#include <iostream>
class Foo
{
public:
Foo(int size) : size_(size),
capacity_(size_ + 2),
length_(capacity_)
{}
void print() {
std::cout << "Size: " << size_ << " Capacity: " << capacity_ << " Length: " << length_ << std::endl;
}
private:
int length_;
int capacity_;
int size_;
};
int main() {
Foo foo(50);
foo.print();
}
在这个例子中,我们试图通过初始化列表中引用其他成员变量的方式来初始化length_、capacity_和size_。然而,由于类成员的初始化顺序是按照它们在类中声明的顺序进行的,可能导致length_与capacity_并没有按照我们期望的方式初始化。
如何解决?
为了避免这种问题,应该遵循以下几点:
1.避免在初始化列表中引用其他成员变量
2.顺序一致性:成员变量的初始化顺序是按照它们在类中声明的顺序
修正示例:
#include <iostream>
class Foo
{
public:
Foo(int size) : size_(size),
capacity_(size_ + 2),
length_(calculateLength(size_))
{}
void print() {
std::cout << "Size: " << size_ << " Capacity: " << capacity_ << " Length: " << length_ << std::endl;
}
private:
int calculateLength(int size) {
return size + 2;
}
private:
int size_;
int capacity_;
int length_;
};
int main() {
Foo foo(50);
foo.print();
}