C++ 命名参数习惯用语 - 未设置字符串属性
c++ named parameter idiom - string property not set
请考虑以下(简单(代码。奇怪的 (?( 行为在main()
例程中,详述如下。
数据类
Packet.h
#include <string>
class Packet {
public:
Packet(int iParam, std::string sParam);
~Packet();
void setInt(int iParam);
void setString(std::string sParam);
private:
int iProperty_;
std::string sProperty_;
};
包.cpp
#include "Packet.h"
using std::string;
Packet::Packet(int iParam, string sParam) : iProperty_(iParam),
sProperty_(sParam) {}
Packet::~Packet() {}
void Packet::setInt(int iParam) {
iProperty_ = iParam;
}
void Packet::setString(std::string sParam) {
sProperty_ = sParam;
}
控制器类
PacketController.h
#include <string>
class PacketController {
public:
PacketController();
~PacketController();
PacketController & andSetInt(int iParam);
PacketController & andSetString(std::string sParam);
private:
Packet packet_;
};
数据包控制器.cpp
#include "PacketController.h"
using std::string;
PacketController::PacketController() : packet_(0, "") {}
PacketController::~PacketController() {}
PacketController & PacketController::andSetInt(int iParam) {
packet_.setInt(iParam);
return *this;
}
PacketController & PacketController::andSetString(string sParam) {
packet_.setString(sParam);
return *this;
}
主((
int main() {
PacketController& ctrlRef = PacketController()
.andSetString("hello world")
.andSetInt(19);
PacketController ctrlVal = PacketController()
.andSetString("hello world")
.andSetInt(19);
PacketController& ctrlRef2 = PacketController();
ctrlRef2.andSetString("hello world")
.andSetInt(19);
return 0;
}
如果在main()
的行return 0;
处暂停执行,则在内部packet_
对象上看到以下值:
ctrlRef - packet_:
iProperty_: 19
sProperty_: ""
ctrlVal - packet_:
iProperty_: 19
sProperty_: "hello world"
ctrlRef2 - packet_:
iProperty_: 19
sProperty_: "hello world"
那么为什么sProperty_
ctrlRef
中packet_
对象上是空的呢?这是否与PacketController
对象初始化时的引用有关?但是,为什么ctrlRef
packet_
对象上的iProperty_
正确设置为19
?
PacketController& ctrlRef = PacketController()
.andSetString("hello world")
.andSetInt(19);
ctrlRef
是指在全表达式评估结束时(在;
处(结束生存期的临时 。ctrlRef2
也可以这样说.
使用它会导致未定义的行为。
另一方面,ctrlVal
是从临时初始化的值。使用它很好。
相关文章:
- C++ 命名参数习惯用语 - 未设置字符串属性
- 如何将字符串属性设置为 QTreeWidgetItem?
- 我如何处理有关输入的字符串大小超过字符数组设置大小的错误?
- C++如何将字符串数组中的一个点设置为枚举变量
- 从C++为字符串函数设置_ENV
- 在给定字符串上使用 tolower() 和 isalpha() 并将其输出设置为另一个字符串
- 通过比较字符设置字符串时出现问题
- 如何在 c++ 中从字符串向量设置类对象
- STD ::设置带有字符串键和潜在效率损失
- 如何调用 GetAltMonthNames 来填充外部区域设置月份字符串的安全数组
- 设置可变值通过字符串引用它
- 仅使用 getName 在主函数中设置字符串名称
- 用设置功能在类中设置字符串
- 如何从十六进制设置字符串值
- 为什么这段代码跳过设置字符串变量的 if 语句
- 使用C/C++设置字符串格式
- C++如何从文件中设置字符串变量
- 设置字符串为v8 Array
- 通过指针在结构中设置字符串时发生C++错误
- 如何在c++类中设置c字符串的默认值