Modern C++ ベストプラクティス
最新C++での推奨パターン.
スマートポインタを優先
// 避ける
int* ptr = new int(42);
delete ptr;
// 推奨
auto ptr = std::make_unique<int>(42); // 自動破棄
Range-based for ループ
// 避ける
for (int i = 0; i < v.size(); ++i) {
std::cout << v[i] << " ";
}
// 推奨
for (auto x : v) {
std::cout << x << " ";
}
const参照でコピー削減
// 避ける
void process(std::vector<int> data) { // コピー発生
for (int x : data) { /* */ }
}
// 推奨
void process(const std::vector<int>& data) { // コピーなし
for (int x : data) { /* */ }
}
例外安全性
#include <iostream>
#include <memory>
class Resource {
public:
void operation() {
// 例外が発生してもスマートポインタは自動破棄
if (/* error */) throw std::runtime_error("エラー");
}
~Resource() { std::cout << "クリーンアップ" << std::endl; }
};
int main() {
try {
auto res = std::make_unique<Resource>();
res->operation();
} catch (const std::exception& e) {
std::cout << "例外: " << e.what() << std::endl;
}
// Resource は自動破棄される
return 0;
}
例外: エラー
クリーンアップ
RAII を活用
#include <iostream>
#include <fstream>
class FileGuard {
private:
std::ofstream file;
public:
FileGuard(const std::string& name) : file(name) {}
void write(const std::string& s) { file << s; }
~FileGuard() { file.close(); } // 自動的に閉じる
};
int main() {
{
FileGuard guard("output.txt");
guard.write("Hello, World!");
} // ファイルが自動的に閉じられる
return 0;
}
ポイント
- 手動 new/delete は避ける
- Range-based for を活用
- const参照でコピー削減
- RAII と例外安全性