当前位置: 首页 > 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.jsqmd.com/news/862508/

相关文章:

  • 数据结构存储与操作:从数组、链表到哈希表与树的性能权衡
  • 19个脉冲神经元实现汽车实时控制:极简SNN控制系统解析
  • DINOv3特征工程实战:构建可解释、可增量、可部署的CV数据科学工作流
  • ROS Noetic下,5分钟搞定Hector SLAM建图(附避坑指南与完整launch文件)
  • 基于Windows Defender遥测数据与机器学习预测恶意软件感染风险
  • ddddocr实战测评:除了字母数字,它还能识别哪些奇葩验证码?(含滑块、点选测试)
  • 从官方demo到真实项目:手把手教你定制uniapp uni-card卡片的样式与交互
  • Unity渐变透明实现原理与跨管线避坑指南
  • 告别Callback Hell!用Kotlin协程重构你的Android网络请求层(附完整代码)
  • DETR训练总找不到目标边界?手把手拆解Conditional DETR的cross-attention,教你精准定位
  • Midjourney V6宝丽来风格实战手册:从提示词结构、--style raw权重分配到CMYK色偏补偿,5大参数公式即刻复刻经典Polaroid质感
  • 构图不是靠感觉!用Fitts定律+格式塔原理验证的Midjourney 6大构图公式(附Python自动构图评分脚本)
  • VAE的隐空间为什么是‘连续’的?一个可视化实验带你理解它与普通自编码器的本质区别
  • 别再折腾超级密码了!2024年电信光猫改桥接,打这个电话最快(附完整话术)
  • RAA在OFDM-ISAC系统中的高精度感知与通信优化
  • 初创公司利用taotoken聚合能力快速原型验证多个ai创意
  • Medium作者收益预测模型:轻量可解释的写作价值评估系统
  • ElevenLabs越南语音效翻车预警:5类高频错误(重音错位、声调丢失、专有名词崩坏)及3步修复法
  • 2026年靠谱的昆山毛坯房装修公司/昆山小户型装修公司售后无忧公司 - 行业平台推荐
  • 2026年评价高的昆山大平层全屋定制/昆山法式风格全屋定制专业公司推荐 - 品牌宣传支持者
  • 裸背图像+CNN:青少年脊柱侧弯AI初筛实战指南
  • QiMeng-TensorOp:自动生成高性能张量运算代码的框架
  • 【计算机毕业设计】基于Springboot的教师工作量管理系统的设计与实现+万字文档
  • 2026年口碑好的合肥老破小装修/合肥家装设计装修专业公司推荐 - 行业平台推荐
  • 你的AD7606数据准吗?聊聊STM32F407数据采集中的那些坑:SPI时序、电源与滤波
  • Unity项目性能优化实战:除了Simplygon,还有哪些轻量级减面工具和技巧?
  • Nginx Proxy Manager实战:用它统一管理我的5个Docker服务(含Stream转发配置)
  • 2026年良心的瑶海装修公司/包河装修公司/合肥大户型装修/合肥装修本地装修推荐 - 行业平台推荐
  • 2026年热门的泉州一站式整装装修公司/泉州别墅大宅装修公司/泉州全案定制装修公司哪家报价透明 - 品牌宣传支持者
  • 2026年性价比高的合肥旧房装修/蜀山装修公司/合肥小户型装修/合肥老房装修人气排行榜 - 品牌宣传支持者