C++ 命名参数习惯用语 - 未设置字符串属性

c++ named parameter idiom - string property not set

本文关键字:设置 字符串 属性 用语 参数 习惯 C++      更新时间:2023-10-16

请考虑以下(简单(代码。奇怪的 (?( 行为在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_: 19sProperty_: ""

ctrlVal - packet_:iProperty_: 19sProperty_: "hello world"

ctrlRef2 - packet_:iProperty_: 19sProperty_: "hello world"

那么为什么sProperty_ctrlRefpacket_对象上是空的呢?这是否与PacketController对象初始化时的引用有关?但是,为什么ctrlRefpacket_对象上的iProperty_正确设置为19

PacketController& ctrlRef = PacketController()
.andSetString("hello world")
.andSetInt(19);

ctrlRef是指在全表达式评估结束时(在;处(结束生存期的临时 。ctrlRef2也可以这样说.

使用它会导致未定义的行为。

另一方面,ctrlVal是从临时初始化的值。使用它很好。