将此指针作为r值使用

问题描述 投票:0回答:1

我有一些代码,虽然我有不好的预感,但似乎还是可以用的。

我的 class Node 有私人成员。

// Node properties
std::string m_keySymbol = "";
float m_nodeWeight = 0.0f;
std::string m_displaySymbol = "";

// Ultimately will be either 0x00 or 0x01.  This is a starting and testable value.
//std::uint8_t m_branchBitValue = 0xFF;

// Node relationships
Node* mp_parentNode = nullptr;

//std::pair<Node*, Node*> mp_childNodes = { nullptr, nullptr };
NodeBranches m_nodeBranches;
bool m_nodeHasBranches = false;

和一个定义为:

Node::Node(Node& left, Node& right) {

    m_keySymbol = left.m_keySymbol + right.m_keySymbol;
    m_nodeWeight = left.m_nodeWeight + right.m_nodeWeight;
    m_displaySymbol = left.m_displaySymbol + right.m_displaySymbol;

    m_nodeHasBranches = true;
    m_nodeBranches.left.first = const_cast<Node*>(&left);
    m_nodeBranches.left.second = 0x00;
    m_nodeBranches.right.first = const_cast<Node*>(&right);
    m_nodeBranches.right.second = 0x01;

    left.mp_parentNode = this;
    right.mp_parentNode = this;
}

我特别关注的是最后的两行字 Node::Node(Node& left, Node& right) 特别是在我使用过的 this 作为r值。

main() 下面的代码工作。

    // Start the combining process.
    Node cb(nodesVector[0], nodesVector[1]);

    std::cout << "Address of cb: " << std::hex << &cb << std::endl;
    std::cout << "Parent node of nodesVector[0]: " << std::hex << nodesVector[0].GetParentNode() << std::endl;

就是说,地址是 cb 匹配。nodesVector[0].GetParentNode(),它返回 mp_parentNode.

我找过了,但找不到一个例子 this 被用作r值,尽管这被定义为具有r值属性的pr值表达式。

我是否遗漏了什么?

c++ this-pointer
1个回答
0
投票

我具体关注的是......特别是我把这个作为rvalue的地方。

这一点没有什么可担心的。正如你所说。this 是一个prvalue表达式。Prvalues是r值,它们只能作为r值使用。

你应该关注的是存储引用参数的指针。很容易意外地使用构造函数,其寿命在构造节点之前结束的对象。我建议使用指针参数来代替,这样对调用者来说,会更清楚地知道将存储一个指向对象的指针。同时要仔细记录。

另外,在 const_cast的是多余的。

© www.soinside.com 2019 - 2024. All rights reserved.