当前位置: 首页 > news >正文

C++const正确性实践

C++const正确性实践

const正确性是C++编程的重要原则,通过const关键字明确表达不可变性,提高代码的安全性和可读性。

const成员函数承诺不修改对象状态,可以被const对象调用。

#include
#include
#include

class Point {
int x_, y_;

public:
Point(int x, int y) : x_(x), y_(y) {}

int x() const { return x_; }
int y() const { return y_; }

void set_x(int x) { x_ = x; }
void set_y(int y) { y_ = y; }

double distance_from_origin() const {
return std::sqrt(x_ * x_ + y_ * y_);
}

void display() const {
std::cout << "(" << x_ << ", " << y_ << ")\n";
}
};

void const_member_function() {
const Point p1(3, 4);
std::cout << "x: " << p1.x() << ", y: " << p1.y() << "\n";
std::cout << "Distance: " << p1.distance_from_origin() << "\n";
p1.display();
}

const引用参数避免拷贝并保证不修改参数。

void print_vector(const std::vector& vec) {
for (int val : vec) {
std::cout << val << " ";
}
std::cout << "\n";
}

int sum_vector(const std::vector& vec) {
int total = 0;
for (int val : vec) {
total += val;
}
return total;
}

void const_reference_params() {
std::vector numbers = {1, 2, 3, 4, 5};
print_vector(numbers);
std::cout << "Sum: " << sum_vector(numbers) << "\n";
}

const返回值防止对临时对象的修改。

class String {
char* data_;

public:
explicit String(const char* str) {
data_ = new char[strlen(str) + 1];
strcpy(data_, str);
}

~String() {
delete[] data_;
}

const char* c_str() const {
return data_;
}

String(const String&) = delete;
String& operator=(const String&) = delete;
};

void const_return_value() {
String s("Hello");
const char* str = s.c_str();
std::cout << "String: " << str << "\n";
}

mutable关键字允许const成员函数修改特定成员。

class Cache {
mutable int access_count_;
mutable bool cached_;
mutable int cached_value_;
int expensive_computation() const {
std::cout << "Computing...\n";
return 42;
}

public:
Cache() : access_count_(0), cached_(false), cached_value_(0) {}

int get_value() const {
++access_count_;
if (!cached_) {
cached_value_ = expensive_computation();
cached_ = true;
}
return cached_value_;
}

int access_count() const {
return access_count_;
}
};

void mutable_example() {
const Cache cache;
std::cout << "Value: " << cache.get_value() << "\n";
std::cout << "Value: " << cache.get_value() << "\n";
std::cout << "Access count: " << cache.access_count() << "\n";
}

const迭代器和const_iterator有不同的含义。

void const_iterators() {
std::vector vec = {1, 2, 3, 4, 5};

for (std::vector::const_iterator it = vec.begin(); it != vec.end(); ++it) {
std::cout << *it << " ";
}
std::cout << "\n";

const std::vector const_vec = {10, 20, 30};
for (auto it = const_vec.begin(); it != const_vec.end(); ++it) {
std::cout << *it << " ";
}
std::cout << "\n";
}

const指针和指向const的指针是不同的概念。

void const_pointers() {
int x = 10;
int y = 20;

const int* ptr1 = &x;
std::cout << "ptr1: " << *ptr1 << "\n";
ptr1 = &y;

int* const ptr2 = &x;
*ptr2 = 30;
std::cout << "x after ptr2: " << x << "\n";

const int* const ptr3 = &x;
std::cout << "ptr3: " << *ptr3 << "\n";
}

const正确性在类设计中确保接口的清晰性。

class Rectangle {
int width_, height_;

public:
Rectangle(int w, int h) : width_(w), height_(h) {}

int width() const { return width_; }
int height() const { return height_; }

int area() const {
return width_ * height_;
}

void set_width(int w) {
width_ = w;
}

void set_height(int h) {
height_ = h;
}

void scale(double factor) {
width_ = static_cast(width_ * factor);
height_ = static_cast(height_ * factor);
}
};

void const_interface_design() {
const Rectangle rect(10, 20);
std::cout << "Area: " << rect.area() << "\n";

Rectangle mutable_rect(5, 10);
mutable_rect.scale(2.0);
std::cout << "Scaled area: " << mutable_rect.area() << "\n";
}

const正确性是编写高质量C++代码的重要实践,它使代码的意图更加明确,减少错误。

http://www.gsyq.cn/news/1343253.html

相关文章:

  • DINOv3特征工程实战:构建可解释、可增量、可部署的CV数据科学工作流
  • C++lambda表达式深入解析
  • ddddocr实战测评:除了字母数字,它还能识别哪些奇葩验证码?(含滑块、点选测试)
  • 从官方demo到真实项目:手把手教你定制uniapp uni-card卡片的样式与交互
  • 告别Callback Hell!用Kotlin协程重构你的Android网络请求层(附完整代码)
  • Vue3项目里SignalR怎么用?一个聊天室Demo带你从配置到上线(.NET 6 + Vue 3)
  • 从自动驾驶到AR:聊聊RANSAC算法在现实世界中的那些‘抗干扰’应用
  • 别再让设备‘闪一下’就重启了!手把手教你用TPS22975搞定浪涌电流(附实测波形)
  • 别再手动画图了!用Mermaid+Markdown在VSCode里5分钟搞定UML设计文档
  • 从单机到团队协作:手把手教你用SVN在Windows上搭建个人小型项目版本库(含汉化与日常使用图解)
  • 2026年良心的瑶海装修公司/包河装修公司/合肥大户型装修/合肥装修本地装修推荐 - 行业平台推荐
  • 2026年次日达的制造业物流/整车物流品质保障公司 - 行业平台推荐
  • Medium作者收益预测模型:轻量可解释的写作价值评估系统
  • 2026年安全的上门取货物流运输/危险品物流运输/整车物流运输可靠服务公司 - 行业平台推荐
  • 从GPT-3到DALL-E:拆解OpenAI的‘数据飞轮’,看CLIP如何成为多模态的基石
  • 构图不是靠感觉!用Fitts定律+格式塔原理验证的Midjourney 6大构图公式(附Python自动构图评分脚本)
  • 基于Windows Defender遥测数据与机器学习预测恶意软件感染风险
  • 【Midjourney印象派风格创作指南】:20年AI视觉专家亲授5大核心参数调优法,3步生成莫奈级画作
  • 2026年时间短的全国直达物流/龙港发全国物流/卡航物流优选公司推荐 - 品牌宣传支持者
  • 大语言模型推理性能优化与混合建模实践
  • QiMeng-TensorOp:自动生成高性能张量运算代码的框架
  • Unity UI粒子渲染技术深度解析与性能优化方案
  • Nginx Proxy Manager实战:用它统一管理我的5个Docker服务(含Stream转发配置)
  • 从MySQL分区到OceanBase分区:迁移老手教你平滑过渡与性能调优
  • 2026年软件开发行业发展趋势:低代码/无代码将成为主流
  • DeepL Chrome翻译插件终极指南:3分钟实现专业级网页翻译
  • 深入Linuxptp ptp4l状态机:从协议原文9.2.5节到代码`ptp_fsm`的映射解析
  • 为Claude Code配置Taotoken作为稳定后备API服务源
  • Taotoken Token Plan套餐如何帮助个人开发者控制预算
  • RNN循环结构实战解析:从时间步展开到门控机制设计