C++中如何初始化指针并为其自行赋值?
C++中先初始化指针再赋值的正确做法
1. 动态内存分配(new/delete)
这是你已经尝试过的方式,核心是先为指针分配有效的内存空间,再进行赋值操作,注意用完后必须手动释放内存避免泄漏:
#include <iostream> #include <string> int main() { std::string* bar = nullptr; // 分配内存并初始化字符串对象 bar = new std::string("world"); std::cout << *bar << std::endl; // 手动释放内存,防止内存泄漏 delete bar; bar = nullptr; // 可选操作,避免指针变成野指针 }
2. 指向栈上已存在的变量
如果不需要动态内存,可以让指针指向一个已经创建好的栈变量,这种方式不需要手动管理内存,变量会在作用域结束时自动销毁:
#include <iostream> #include <string> int main() { std::string* bar = nullptr; std::string foo; // 在栈上创建字符串变量 bar = &foo; // 让指针指向foo的内存地址 *bar = "world"; // 此时解引用赋值是安全的 std::cout << *bar << std::endl; std::cout << foo << std::endl; // 结果与*bar一致 }
3. 使用智能指针(现代C++推荐方案)
智能指针可以自动管理内存,避免手动调用delete时遗忘导致的内存泄漏,是更安全的选择:
独占型智能指针unique_ptr
适用于单个指针独占对象所有权的场景:
#include <iostream> #include <string> #include <memory> int main() { std::unique_ptr<std::string> bar = nullptr; // 分配内存并初始化,智能指针自动管理生命周期 bar = std::make_unique<std::string>("world"); std::cout << *bar << std::endl; // 无需手动释放内存,智能指针在作用域结束时自动销毁对象 }
共享型智能指针shared_ptr
适用于多个指针需要共享同一对象所有权的场景:
#include <iostream> #include <string> #include <memory> int main() { std::shared_ptr<std::string> bar = nullptr; bar = std::make_shared<std::string>("world"); std::cout << *bar << std::endl; }
核心注意事项
- 绝对不能对未初始化的指针或**空指针(nullptr)**直接解引用赋值(
*bar = ...),这类操作会触发未定义行为或段错误,本质是指针没有指向有效的内存空间。 - 用
new分配的内存必须匹配delete释放,否则会造成内存泄漏;智能指针则通过自动回收机制规避了这个问题。
内容的提问来源于stack exchange,提问作者Alec Mather
相关产品推荐
相关产品推荐

